sql server查询计数数据

时间:2014-07-03 17:54:24

标签: sql sql-server sql-server-2008

这是我的表1:

a   b   c
100 110 1
200 0   2
300 150 3
100 0   2
200 300 2
300 106 3

我希望将结果显示为:

abc xyz
2   P
2   U
2   PL

这是因为

将行(其中,b> a)作为P并且将(b ='0')计为U并且将(b <= a和b!='0')计为PL。 问题是如何显示这些值,如P,U,PL这些值在我的Table1中不存在。 所以我如何像这样展示我的桌子

abc xyz
 2  P
 2  U
 2  PL

我正在使用SQL Server 2008。

3 个答案:

答案 0 :(得分:0)

使用案例陈述

SELECT Count(*) as abc, CASE WHEN b= 0 THEN 'U'
    WHEN b>a THEN 'P'
    ELSE 'PL' END as xyz
FROM [Table 1]
GROUP BY
CASE WHEN a>b THEN 'P'
    WHEN b=0 THEN 'U'
    ELSE 'PL' END

答案 1 :(得分:0)

select count(*) as abc, symbol as xyz
from (
SELECT CASE WHEN b > a AND b != 0 THEN 'P'
    WHEN b=0 THEN 'U'
    ELSE 'PL' END as symbol
FROM [Table 1]
) as aa
group by symbol

答案 2 :(得分:0)

您可以将结果合并在一起。

SELECT COUNT(1) AS abc ,'P' AS xyz
FROM #temp
WHERE a > b
AND b != 0
UNION
SELECT COUNT(1) AS abc, 'U' AS xyz
FROM #temp
WHERE b = 0
UNION
SELECT COUNT(1) AS abc, 'PL' AS xyz
FROM #temp
WHERE b<= a
AND b != 0

我必须在您的P条件中添加b!= 0以符合您的预期结果。