Count the total records containing specific values

纵然是瞬间 提交于 2019-12-09 16:30:14

问题


I have a question and hope you guys can assist me.

I have a table containing two columns:

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

I need to make a view that returns values like this:

TYPE:RAID     ACCEPTED:5          DENIED:7

Basically I want to know how many of the values in TYPE are "Raid" and then how many of them are "Accepted" and "Denied".

Thank you in advance!!


回答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:


This code should work for mySQL

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

or

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



回答3:


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

for total number of type=raid

Are you saying something like this?




回答4:


You can use COUNT in combination with a CASE statement

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 …) is also possible, but you'll have to return 0 in the ELSE clause instead of NULL




回答5:


Hey this might help:-

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;


来源:https://stackoverflow.com/questions/9998220/count-the-total-records-containing-specific-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!