TSQL Question: Group by on multiple columns
I have a table with multiple columns that represent occurrences of an action.
simpleTableExample
id type $$$$$ value1 value2 value3 ... value15
-- ---- -- ----- ----- ----- -----
1 "I" 1 "a" "b" "" ""
2 "O" 1 "a" "d" "f" "z"
3 "I" 1 "d" "b" "" ""
4 "O" 1 "g" "l" "" ""
5 "I" 1 "z" "g" "a" ""
6 "I" 1 "z" "g" "a" "a"
not really sure how to represent the data, but the above should show it... Per row, I have multiple columns that I want to group by. Focusing on the "a" part, I'd like the output such that :
Type Value Count Sum
----- ----- ----- ---
"I" "A" "3" 3
"O" "A" "2" 1
Just not sure how to go about, or even the best way, to group by with multiple columns. If it was a "tall" table with a sequence number, it'd be a snap...
One thing I'm worried about... is if I have the same value in multiple rows (they have the same action done multiple times), and I stack the columns and try to sum rows. So for example row 6 has 3 and 15 with value of a, and I try to Sum() the totals of that group, I don't want 6 counted twice (shown above
Edit: Trying to clarify here... I have a row of customers with "actions". The actions are collapsed into value1 thru value15. I want to get a co开发者_JAVA技巧unt of "type, value" groups.
The count I had earlier was wrong... I want the distinct customers that have had a certain action, not the number of certain actions. So I-A should be a count of 4, using the above visible table.
Final NoteCode Review question for what I came up with. Unpivot to build a list of unique date/value pairs.
Assuming SQL 2005 or greater you can use UNPIVOT and then do your GROUP BYs and COUNTs
Do you have the option to put that table in First Normal Form and break those repeating columns out to a child table? Because, if we put aside the theory of why 1NF is good, the practical reality is that non-normalized examples like this make simple queries tough.
With that being said, if you are stuck with this non-normalized table, you have to code up something like this:
select type
, 'A' as Column2
, sum(case when value1='A' or value2='A' or.....
then 1 else 0 end) as theCount
from theTable
group by type
If you want to query for multiple values, not just 'A', you have to pivot the table in the query, which involves oh about 15 unions:
select type,value,count(*) from (
select type,value1 as value from theTable
union all
select type,value2 as value from theTable
union all
select type,value3 as value from theTable
...and so on...
) x
group by type,value
精彩评论