CustomerData.sql 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. IF OBJECT_ID ('dbo.CustomerData','V') IS NOT NULL DROP VIEW dbo.CustomerData
  2. GO
  3. CREATE VIEW dbo.CustomerData
  4. AS
  5. SELECT b.CompanyID,
  6. b.BAccountID as SurrogateBAKey,
  7. b.AcctCD as CustomerID,
  8. b.AcctName as CustomerName,
  9. p.AcctCD as ParentAccountID,
  10. bke.ValueString as OwnerID,
  11. count(children.BAccountID) as CountOfChildrenAccounts,
  12. STRING_AGG(children.AcctCD, ', ') AS ChildrenIDList,
  13. CAST(CASE
  14. WHEN COUNT(children.BAccountID) > 0 THEN 1
  15. ELSE 0
  16. END AS BIT) AS IsParent,
  17. CAST(CASE
  18. WHEN MAX(CASE WHEN b.ParentBAccountID IS NOT NULL THEN 1 ELSE 0 END) = 1 THEN 1
  19. ELSE 0
  20. END AS BIT) AS IsChild
  21. From BAccount b
  22. left JOIN BAccount p on p.CompanyID = b.CompanyID and p.BAccountID = b.ParentBAccountID
  23. LEFT join BAccount children on children.CompanyID = b.CompanyID and b.BAccountID = children.ParentBAccountID and b.[type] = children.[type]
  24. LEFT JOIN BAccountKvExt bke ON bke.CompanyID = b.CompanyID AND bke.RecordID = b.NoteID AND bke.FieldName = 'AttributeOWNER'
  25. where b.[type] = 'CU'
  26. group by b.CompanyID,
  27. b.BAccountID,
  28. b.AcctCD,
  29. b.AcctName,
  30. p.AcctCD,
  31. bke.ValueString