计算包含特定值的总记录数

时间:2012-04-03 17:19:46

标签: sql count case conditional-statements

我有一个问题,希望你们能帮助我。

我有一个包含两列的表:

type           // contains 2 different values: "Raid" and "Hold"
authorization  // contains 2 different values: "Accepted" or "Denied"

我需要创建一个返回如下值的视图:

TYPE:RAID     ACCEPTED:5          DENIED:7

基本上我想知道TYPE中有多少值是“Raid”然后有多少 他们是“接受”和“拒绝”。

提前谢谢!!

5 个答案:

答案 0 :(得分:11)

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

答案 1 :(得分:4)

此代码适用于mySQL

SELECT type, COUNT(*)
FROM table
GROUP BY type;

SELECT type, authorization, COUNT(*)
FROM table
GROUP BY type, authorization;

答案 2 :(得分:2)

您可以将COUNTCASE声明结合使用

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 …)也可以,但您必须在0子句中返回ELSE而不是NULL

答案 3 :(得分:1)

select count(*) as count from tbl_name where type='Raid'

表示type = raid的总数

你是说这样的话吗?

答案 4 :(得分:0)

嘿,这可能会有所帮助: -

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;