I am trying to merge a list of accounts from different sources and identify which account codes are set up identically across all sources.
Here is the code:
SELECT
Distinct a.MainCode,
a.Type,
a.Group,
a.InternalCode
FROM 700_AccountTable a
Left join 700_AccountDetail b
on a.MainCode = b.MainCode
Left join 700_AccountHistory c
on a.AccountKey = c.AccountKey
Where
b.Status = 'Active'
GROUP BY
a.MainCode,
a.Type,
a.Group,
a.InternalCode
HAVING
count(c.AccountKey) > 0
UNION
SELECT
Distinct a.MainCode,
a.Type,
a.Group,
a.InternalCode
FROM 111_AccountTable a
Left join 111_AccountDetail b
on a.MainCode = b.MainCode
Left join 111_AccountHistory c
on a.AccountKey = c.AccountKey
Where
b.Status = 'Active'
GROUP BY
a.MainCode,
a.Type,
a.Group,
a.InternalCode
HAVING
count(c.AccountKey) > 0
Here is the current output:
| MainCode | Type | Group | InternalCode |
|---|---|---|---|
| 3010 | 11 | 3000 | 700 |
| 3010 | 11 | 3000 | 111 |
| 3020 | 11 | 3000 | 700 |
| 3020 | 11 | 3000 | 111 |
| 3030 | 11 | 3000 | 111 |
| 3070 | 11 | 3000 | 111 |
| 3070 | 11 | 3000 | 700 |
| 3070 | 12 | 3000 | 700 |
This is the desired output:
| MainCode | Type | Group | 700 | 111 |
|---|---|---|---|---|
| 3010 | 11 | 3000 | X | X |
| 3020 | 11 | 3000 | X | X |
| 3030 | 11 | 3000 | X | |
| 3070 | 11 | 3000 | X | X |
| 3070 | 12 | 3000 | X |
Your current query has syntax error. As group is a reserved keyword in SQL; While using it in sql server as a column name; surround it using square brackets.
Using your original query and replacing
Groupby [Group]We can PIVOT the
InternalCodecolumn as follows :As I don't have your original data; I used the result of your union query to create a table and work on.
Here is a working solution using SQLFIDDLE
This returns the expected result:
You can also do it using PIVOT function in SQL Server as :
Here is a working demo using your current table data :