如何为此编写sql查询?
我的桌子看起来像这样:如何为此编写sql查询?,sql,sql-server,tsql,Sql,Sql Server,Tsql,我的桌子看起来像这样: id staus 1 p 1 p 1 c 2 p 2 c id p c 1 2 1 <-- id 1 has two rows with 'p' and one row with 'c' 2 1 1 <-- id 2 has one row with 'p' and one row with 'c' SELECT id , SUM (CASE STATUS WHEN 'p'
id staus
1 p
1 p
1 c
2 p
2 c
id p c
1 2 1 <-- id 1 has two rows with 'p' and one row with 'c'
2 1 1 <-- id 2 has one row with 'p' and one row with 'c'
SELECT
id
, SUM (CASE STATUS WHEN 'p' THEN 1 ELSE 0 END) as p
, SUM (CASE STATUS WHEN 'c' THEN 1 ELSE 0 END) as c
FROM my_table
GROUP BY id
我需要为每个id
生成状态为'p'
和'c'
的行计数,因此我期望的结果如下所示:
id staus
1 p
1 p
1 c
2 p
2 c
id p c
1 2 1 <-- id 1 has two rows with 'p' and one row with 'c'
2 1 1 <-- id 2 has one row with 'p' and one row with 'c'
SELECT
id
, SUM (CASE STATUS WHEN 'p' THEN 1 ELSE 0 END) as p
, SUM (CASE STATUS WHEN 'c' THEN 1 ELSE 0 END) as c
FROM my_table
GROUP BY id
idpc
1 2你可以这样做:
id staus
1 p
1 p
1 c
2 p
2 c
id p c
1 2 1 <-- id 1 has two rows with 'p' and one row with 'c'
2 1 1 <-- id 2 has one row with 'p' and one row with 'c'
SELECT
id
, SUM (CASE STATUS WHEN 'p' THEN 1 ELSE 0 END) as p
, SUM (CASE STATUS WHEN 'c' THEN 1 ELSE 0 END) as c
FROM my_table
GROUP BY id
如果要聚合的固定项不止是几个,例如'p'
和'c'
,则可能会提供更好的选择。似乎需要对表进行透视,当我遇到同样的问题时,我使用了一篇简单的文章。从SQLServer2008开始工作
declare @t table(id int, staus char(1))
insert @t values( 1,'p'),( 1,'p'),( 1,'c'),( 2,'p'),( 2,'c')
SELECT id, [p], [c]
from @t
PIVOT
(count([staus])
FOR staus
in([p],[c])
)AS p
结果:
id p c
1 2 1
2 1 1
它还有助于提供表定义。