gpt4 book ai didi

sql - SQL Server 2008 中的大小写和计数

转载 作者:行者123 更新时间:2023-12-02 17:22:01 24 4
gpt4 key购买 nike

我有一个表,存储一个州的多个项目,我想根据特定条件获取每个州的计数。我写了这个查询:

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

但我收到此错误:

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

当我为 State_ID 添加 GROUP BY 子句时,State_Name 再次出现上述错误,当我将 State_Name 添加到 GROUP BY 子句时,我收到 State_All、State_w 错误,State_s。

我的表中没有名为 State_All、State_w、State_s 的列。

如何在不使用CURSORS的情况下根据特定条件获取计数?

最佳答案

你走在正确的道路上。

您可以像这样将条件放入 COUNT 中。 COUNT 忽略 NULL(这是 CASE 中隐含的 ELSE),因此您只计算真正的匹配项。您还需要 GROUP BY。

您的错误来自于在 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

关于sql - SQL Server 2008 中的大小写和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7226646/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com