简体   繁体   English

如何形成这个sql查询?

[英]How to form this sql query?

SELECT state,count(*) as regular 
FROM X 
group by state

This gives a result like这给出了一个结果

AL 10
AK 20 
AZ 25

SELECT state,count(*) as regular 
FROM X 
where alcohol_use=TRUE 
group by state

This gives a result like这给出了一个结果

AL 5
AK 10
AZ 20

I need a single query which finds out the percentage and provides me an output like我需要一个查询来找出百分比并为我提供类似的输出

AL 50%
AK 50%
AZ 80%

Thanks in advance提前致谢

  SELECT state,
         SUM(alcohol_use=TRUE) / COUNT(*) * 100
    FROM X
GROUP BY state

SUM(alcohol_use=TRUE) expression would add up values of alcohol_use=TRUE which is either true or false which is then implicitly casted to 1 or 0 accordingly. SUM(alcohol_use=TRUE)表达式会加起来alcohol_use=TRUE值,它是truefalse ,然后相应地隐式转换为10

One way of achieving this "partial count" is to sum a case expression with your condition.实现此“部分计数”的一种方法是将case表达式与您的条件相加。 Eg:例如:

SELECT   state, 
         SUM (CASE alcohol_use WHEN TRUE THEN 1 ELSE 0 END) / COUNT(*) as percent
FROM     x
GROUP BY state

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM