计算包含特定值的总记录
Posted
技术标签:
【中文标题】计算包含特定值的总记录【英文标题】:Count the total records containing specific values 【发布时间】:2012-04-17 09:35:30 【问题描述】:我有一个问题,希望你们能帮助我。
我有一个包含两列的表格:
type // contains 2 different values: "Raid" and "Hold"
authorization // contains 2 different values: "Accepted" or "Denied"
我需要创建一个返回如下值的视图:
TYPE:RAID ACCEPTED:5 DENIED:7
基本上我想知道TYPE
中有多少值是“Raid”,然后有多少
它们是“接受”和“拒绝”。
提前谢谢你!!
【问题讨论】:
【参考方案1】:SELECT
Type
,sum(case Authorization when 'Accepted' then 1 else 0 end) Accepted
,sum(case Authorization when 'Denied' then 1 else 0 end) Denied
from MyTable
where Type = 'RAID'
group by Type
【讨论】:
【参考方案2】:您可以将COUNT
与CASE
语句结合使用
SELECT COUNT(CASE authorization WHEN 'denied' THEN 1 ELSE NULL END) as denied,
COUNT(CASE authorization WHEN 'authorized' THEN 1 ELSE NULL END) as authorized
FROM table
WHERE type = 'RAID'
SUM(CASE …)
也是可能的,但您必须在 ELSE
子句中返回 0
而不是 NULL
【讨论】:
这不会像这样工作。 CASE WHEN 需要一个 END 来完成块。 @Magisch:是的,你是对的。感谢您指出,我已经修复了 sn-p!【参考方案3】:这段代码应该适用于 mysql
SELECT type, COUNT(*)
FROM table
GROUP BY type;
或
SELECT type, authorization, COUNT(*)
FROM table
GROUP BY type, authorization;
【讨论】:
【参考方案4】:select count(*) as count from tbl_name where type='Raid'
type=raid 的总数
你是在说这种话吗?
【讨论】:
【参考方案5】:嘿,这可能会有所帮助:-
select type as 'TYPE',sum(Denied) as 'DENIED',sum(Accepted) as 'AUTHORIZED' from
(
SELECT type,0 as 'Denied',count(*) as 'Accepted' from t where authorization = 'Accepted' group by type
union all
SELECT type,count(*) as 'Denied',0 as 'Accepted' from t where authorization = 'Denied' group by type ) as sub_tab group by TYPE;
【讨论】:
干草是给马用的。以上是关于计算包含特定值的总记录的主要内容,如果未能解决你的问题,请参考以下文章
SQL:计算每个设备集连续出现相同值的所有记录并返回最高计数