我有一个名为Work
的表格,其中有两列 - Name
和Status
:
SELECT Name,Status FROM Work
--------+----------
Name |Status
--------+----------
MyBJE |2
MyBJE_2 |9
MyBJE |8
MyBJE_2 |9
MyBJE |7
MyBJE_2 |9
MyBJE |2
MyBJE |8
MyBJE_2 |3
MyBJE |8
MyBJE |8
MyBJE_2 |1
MyBJE_2 |8
MyBJE |4
我试图找出如何编写查询,这将从上述数据中返回以下结果:
--------+-------+-------+-------
Name |COUNT_2|COUNT_3|COUNT_4
--------+-------+-------+-------
MyBJE |2 |0 |1
MyBJE_2 |0 |1 |0
预期的语义如下:
这是我到目前为止所做的(数据来自真实的数据库,而不是上面的例子)。
SELECT Name, Status, COUNT(1)
FROM (SELECT Name, (CASE when Status IN (2,3,4) then Status else 0 end) as Status FROM Work) x
GROUP BY Name, Status
--------+------+----------------
Name |Status|(No column name)
--------+------+----------------
MyBJE_2 |0 |262
MyBJE_2 |2 |1033
MyBJE |0 |2496
现在我知道我应该使用PIVOT语句,但我无法弄清楚如何。
答案 0 :(得分:1)
Select name,
sum(case when status=2 then 1 else 0 end) as Count_2,
sum(case when status=3 then 1 else 0 end) as Count_3,
sum(case when status=4 then 1 else 0 end) as Count_4
from work
group by name
答案 1 :(得分:0)
select Name,sum(Case when Status=2 then 1 Else 0 End) Count_2,sum(Case when Status=3 then 1 Else 0 End) Count_3,
sum(Case when Status=4 then 1 Else 0 End) Count_3
From tableName
where Status in(2,3,4)
Group By Name