场景是我在表中有一个名为“States”的列,状态可以是0,1,2,3或4.我想要做的是使用WHERE State =
计算每个州的状态单个查询。
主要目的是我想显示记录的数量(由他们的州确定)。像这样, 20条记录的状态为0 等。
这可能吗?如果是,那我该如何实现呢?
编辑:我知道Count
。这是我尝试过的:
SELECT State, Date_Created, (SELECT COUNT(Id) FROM [ECOS].[eco].[tb_projects_details] WHERE State=1) as State_One, (SELECT COUNT(Id) FROM [ECOS].[eco].[tb_projects_details] WHERE State=2) as State_Two, (SELECT COUNT(Id) FROM [ECOS].[eco].[tb_projects_details] WHERE State=0) as State_Zero, (SELECT COUNT(Id) FROM [ECOS].[eco].[tb_projects_details] WHERE State=4) as State_Four FROM [ECOS].[eco].[tb_projects_details] WHERE Date_Created < dateadd(week,-3,getdate());
答案 0 :(得分:1)
要生成值列表及其计数,您可以执行以下操作:
SELECT State, COUNT(*) AS C
FROM mytable
GROUP BY State
要生成一行包含值计数作为列的行,您可以执行以下操作:
SELECT
COUNT(CASE State WHEN 0 THEN 1 ELSE NULL END) AS State_0_Count,
COUNT(CASE State WHEN 1 THEN 1 ELSE NULL END) AS State_1_Count,
COUNT(CASE State WHEN 2 THEN 1 ELSE NULL END) AS State_2_Count,
COUNT(CASE State WHEN 3 THEN 1 ELSE NULL END) AS State_3_Count,
COUNT(CASE State WHEN 4 THEN 1 ELSE NULL END) AS State_4_Count
FROM [...]
WHERE [...]
答案 1 :(得分:1)
如果我理解正确,你想分组并计算:
SELECT mt.States, COUNT(*) total
FROM my_table mt
GROUP BY mt.States
答案 2 :(得分:1)
如果在group by
条件之后使用where
子句,那将非常容易。然后,您将很容易得到每个州的数量。
SELECT state, count(*)
FROM table_name
GROUP BY state
答案 3 :(得分:0)
下次首先阅读sql for beginners book。
Select state, count(*)
from table
group by state