我有一个名为" status"在一个名为"最新"的sql表中其中包含五个不同的新值,已部署,已解决,已分配和已关闭,如下所示
Status
--------------
NEW
NEW
DEPLOYED
NEW
RESOLVED
ASSIGNED
ASSIGNED
RESOLVED
ASSIGNED
NEW
NEW
RESOLVED
CLOSED
ASSIGNED
我想写一个查询,我可以在其中计算每个单词出现在" status"列中的次数。目前我在5个不同的查询中使用了count函数。
1)select count(status) from latest where status="NEW";
2)select count(status) from latest where status="DEPLOYED";
3)select count(status) from latest where status="RESOLVED";
4)select count(status) from latest where status="ASSIGNED";
5)select count(status) from latest where status="CLOSED";
有没有办法可以将所有这些查询组合成单个查询而不使用连接或联合来获得5个不同的计数值?
答案 0 :(得分:1)
QUERY 1:
SELECT STATUS, COUNT(1) FROM LATEST
GROUP BY STATUS
ORDER BY STATUS;
您的输出将是:
STATUS COUNT
ASSIGNED 4
CLOSED 1
DEPLOYED 1
NEW 5
RESOLVED 3
要获得包含5列的单行输出,您可以使用: QUERY 2:
SELECT COUNT(CASE WHEN STATUS='ASSIGNED' THEN 1 END) ASSIGNED_COUNT,
COUNT(CASE WHEN STATUS='CLOSED' THEN 1 END) CLOSED_COUNT,
COUNT(CASE WHEN STATUS='DEPLOYED' THEN 1 END) DEPLOYED_COUNT,
COUNT(CASE WHEN STATUS='NEW' THEN 1 END) NEW_COUNT,
COUNT(CASE WHEN STATUS='RESOLVED' THEN 1 END) RESOLVED_COUNT
FROM LATEST
您的输出将是:
ASSIGNED_COUNT | CLOSED_COUNT | DEPLOYED_COUNT | NEW_COUNT | RESOLVED_COUNT
4 | 1 | 1 | 5 | 3
<强>说明强>
查询1 可以在可以有任意数量的动态状态的情况下使用。例如,即使存在名为DEFERRED的状态,也会自动包含该状态而不更改查询。但是,如果有说,没有状态为“NEW”的记录,则不会返回任何数据。
查询2 可用于返回单行中的所有数据。如果要包含新状态,则必须修改查询。如果状态没有记录,则返回0。 IDEAL FOR DASHBOARD 用途。
答案 1 :(得分:0)
试试这个:
SELECT l.status, COUNT(1)
FROM latest l
GROUP BY l.status;
或强>
SELECT SUM(l.status = 'NEW') AS NEW_STATUS,
SUM(l.status = 'DEPLOYED') AS DEPLOYED_STATUS,
SUM(l.status = 'RESOLVED') AS RESOLVED_STATUS,
SUM(l.status = 'ASSIGNED') AS ASSIGNED_STATUS,
SUM(l.status = 'CLOSED') AS CLOSED_STATUS
FROM latest l;
<强>更新强>
使用SELECT...INTO
语句来实现此目的,请查看以下查询
SELECT SUM(l.status = 'NEW') AS NEW_STATUS,
SUM(l.status = 'DEPLOYED') AS DEPLOYED_STATUS,
SUM(l.status = 'RESOLVED') AS RESOLVED_STATUS,
SUM(l.status = 'ASSIGNED') AS ASSIGNED_STATUS,
SUM(l.status = 'CLOSED') AS CLOSED_STATUS
INTO NEW_STATUS, DEPLOYED_STATUS, RESOLVED_STATUS,
ASSIGNED_STATUS, CLOSED_STATUS
FROM latest l;
答案 2 :(得分:0)
尝试这个很酷的
Select *
from
(
Select Status,COUNT(*) 'Count'
from LATEST
group by Status with rollup
) t
where t.Count is not null
答案 3 :(得分:0)
试试这个...
1&GT;
选择计数()作为计数,状态从最新位置(状态=&#39;新&#39;或状态=&#39;部署&#39;或状态=&#39;已解决&#39;或状态=&#39;已分配&#39;或状态=&#39;已关闭&#39;)按状态分组; *
OR
2&GT; 从最新的位置选择计数(状态)(状态=&#39;新&#39;或状态=&#39;部署&#39;或状态=&#39;已解决&#39;或状态=&#39 ;已分配&#39;或状态=&#39;已关闭&#39;);