这是一张桌子
A B C D R
'a' 1 3 1 0
'a' 2 3 1 1
'a' 2 3 1 0
'b' 1 3 1 1
'b' 2 4 3 2
'b' 1 4 3 0
'c' 2 4 3 0
R与A的交叉表如下:
A R count
a 0 2
a 1 1
a 2 0
b 0 1
b 1 1
b 2 1
c 0 1
c 1 0
c 2 0
交叉制表给出了R的频率取决于A。
此操作的sql查询是什么?
答案 0 :(得分:2)
我会使用CROSS JOIN
和LEFT JOIN
select ta.a, tr.r, count(t.a)
from (select distinct a from tab) TA
cross join (select distinct r from tab) TR
left join tab t on t.a = ta.a and t.r = tr.r
group by ta.a, tr.r
答案 1 :(得分:0)
使用CROSS JOIN和条件总和来实现计数:
declare @Table table (A char(1), B int, C int, D int, R int)
Insert into @Table values
('a', 1, 3, 1, 0)
, ('a', 2, 3, 1, 1)
, ('a', 2, 3, 1, 0)
, ('b', 1, 3, 1, 1)
, ('b', 2, 4, 3, 2)
, ('b', 1, 4, 3, 0)
, ('c', 2, 4, 3, 0)
select A, x.R, Sum(iif(x.r = t.R, 1, 0))
from @Table t
cross join (Select distinct R from @Table) x
group by A, x.R
order by a, x.R