Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何为此编写sql查询?_Sql_Sql Server_Tsql - Fatal编程技术网

如何为此编写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

它还有助于提供表定义。