SQL count multiple cells as combination -
i have following sql table shows case number , value, case number appear 2 cases in group, want count how many combinations same case number appearing in table. ware order different, see case , c, both of them should count same combination.
case value 1992 1956 b 2000 b 2001 c 1956 c 1992
the goal total number of each combination, output format doesn't matter. 1 of expected result:
seq value frequency 1 1992 2 1 1956 2 2 2000 1 2 2001 1
what if there 3 cases combination?
this works number of values case. increment frequency count when cases have same number of values , each 1 have match, no matter in order.
create table #table1 ([case] varchar(1), [value] int) ; insert #table1 ([case], [value]) values ('a', 1992), ('a', 1956), ('a', 1997), ('b', 2000), ('b', 2001), ('c', 1956), ('c', 1992), ('c', 1997), /*('c',1993),*/ ('d', 2005), ('d', 2008), ('e', 1956), ('e', 1992) , ('f', 1956), ('f', 1992), ('g', 1956), ('g', 1992) ; --query select min(a.[case]) [case], [values], count(*) frequency ( select t.[case], stuff( ( select ',' + cast (t1.[value] varchar(20)) #table1 t1 t1.[case] = t.[case] order t1.[value] xml path('') ),1,1,'') [values] #table1 t group t.[case] )a group [values] order [case]
result whith values sorted in ascending order
case values frequency a 1956,1992,1997 2 b 2000,2001 1 d 2005,2008 1 e 1956,1992 3
Comments
Post a Comment