Count distinct values on sevaral fields
Count distinct values on sevaral fields
(OP)
Hi, I have a sort of stupid table structure on the project I inherited. It's a list of what work was performed that uses codes like this:
CustomerID | Date | Code1 | Code2 | Code3 | Code4
I want to know all work that was performed for a certain period and thus need to count the distinct codes on codes 1-4.
Say I have the test data:
1 | today | AA | AB | AC | Null
2 | today | AC | BB | Null | Null
I want to get the following:
AA | 1
AB | 1
AC | 2
BB | 1
The table is pretty huge so I need an effective query... Any hints?
CustomerID | Date | Code1 | Code2 | Code3 | Code4
I want to know all work that was performed for a certain period and thus need to count the distinct codes on codes 1-4.
Say I have the test data:
1 | today | AA | AB | AC | Null
2 | today | AC | BB | Null | Null
I want to get the following:
AA | 1
AB | 1
AC | 2
BB | 1
The table is pretty huge so I need an effective query... Any hints?
graabein
RE: Count distinct values on sevaral fields
CODE
, COUNT(*) AS daCount
FROM ( SELECT Code1 AS daCode
FROM daTable
WHERE Code1 IS NOT NULL
UNION ALL
SELECT Code2
FROM daTable
WHERE Code2 IS NOT NULL
UNION ALL
SELECT Code3
FROM daTable
WHERE Code3 IS NOT NULL
UNION ALL
SELECT Code4
FROM daTable
WHERE Code4 IS NOT NULL
) AS d
GROUP
BY daCode
r937.com | rudy.ca
Buy my new book Simply SQL from Amazon
RE: Count distinct values on sevaral fields
CODE
select Code1 as Code from table1
union all
select Code2 as Code from table1
) as Work
where Work.Code is not null
group by Work.Code
What do you think?
graabein
RE: Count distinct values on sevaral fields
graabein