简体   繁体   English

SQL Server 2008中的案例和计数

[英]Case and Count in SQL Server 2008

I have a table that stores multiple items for a state and I want to get count for every states according to specific conditions. 我有一个表存储状态的多个项目,我想根据具体情况计算每个状态。 I wrote this query: 我写了这个查询:

SELECT
    State_ID,
    State_Name,
    State_All= CASE WHEN type1=1 AND type2=1 THEN COUNT(Id) END
    State_w= CASE WHEN type1=2 AND type2=1 THEN COUNT(Id) END
    State_s= CASE WHEN type1=2 AND type2=2 THEN COUNT(Id) END
FROM
    tblStates

but I get this Error: 但我得到这个错误:

Column 'State_ID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

When I added GROUP BY clause For State_ID,I got above error again for State_Name,and when added State_Name to GROUP BY clause ,I got error for State_All,State_w,State_s. 当我为State_ID添加GROUP BY子句时,我再次获得了State_Name的错误,并且当将State_Name添加到GROUP BY子句时,我收到了State_All,State_w,State_s的错误。

I don't have a column called State_All,State_w,State_s in my table. 我的表中没有名为State_All,State_w,State_s的列。

How I can get count according to specific conditions without using CURSORS ? 如何在不使用CURSORS情况下根据具体情况进行计数?

You were on the right path. 你是在正确的道路上。

You put the condition inside the COUNT like this. 你把条件放在COUNT里面就像这样。 COUNT ignores NULLs (which is the implied ELSE in the CASE) so you only count true matches. COUNT忽略NULL(这是CASE中隐含的ELSE),因此您只计算真正的匹配。 You need the GROUP BY too. 你也需要GROUP BY。

Your error comes from the use of type1 and type2 outside of the COUNT 您的错误来自在COUNT之外使用type1和type2

SELECT
    State_ID,
    State_Name,
    State_All = COUNT(CASE WHEN type1=1 AND type2=1 THEN 1 END), 
    State_w = COUNT(CASE WHEN type1=2 AND type2=1 THEN 1 END), 
    State_s = COUNT(CASE WHEN type1=2 AND type2=2 THEN 1 END)
FROM
    tblStates
GROUP BY
    State_ID, State_Name

You can change Count to SUM because each record result 1 您可以将Count更改为SUM,因为每个记录结果为1

SELECT
    State_ID,
    State_Name,
    State_All = SUM(CASE WHEN type1=1 AND type2=1 THEN 1 END), 
    State_w = SUM(CASE WHEN type1=2 AND type2=1 THEN 1 END), 
    State_s = SUM(CASE WHEN type1=2 AND type2=2 THEN 1 END)
FROM
    tblStates
GROUP BY
    State_ID, State_Name

您应该在查询的末尾添加两列:

GROUP BY State_ID, State_Name

Would this fix it? 这会解决它吗?

SELECT
   State_ID,
   State_Name,
   CASE WHEN type1=1 AND type2=1 THEN COUNT(Id) END AS State_All,
   CASE WHEN type1=2 AND type2=1 THEN COUNT(Id) END AS State_w,
   CASE WHEN type1=2 AND type2=2 THEN COUNT(Id) END AS State_s
FROM
   tblStates
GROUP BY State_ID, State_Name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM