我有users_details表,其中包含以下列
martial_status | religion | education
我想从这个表中获取数值,如下所示。
married (100)
single (200)
Muslim(50)
Jews (50)
Christian(50)
Graduates(100)
etc, etc.
我不知道是否可以使用单个SELECT获取所有计数,请帮忙。
答案 0 :(得分:1)
这不是一个SELECT
- 语句,但您可以使用以下一个查询检索它(假设列是兼容的):
( SELECT `martial_status`, COUNT(*) as `cnt` FROM user_details GROUP BY `martial_status` )
UNION
( SELECT `religion`, COUNT(*) as `cnt` FROM user_details GROUP BY `religion` )
UNION
( SELECT `education `, COUNT(*) as `cnt` FROM user_details GROUP BY `education` )
答案 1 :(得分:1)
你需要分别处理每一列,然后联合itp>
SELECT martial_status, count(*)
FROM USER_DETAILS
GROUP BY martial_status
UNION ALL
SELECT religion, count(*)
FROM USER_DETAILS
GROUP BY religion
UNION ALL
SELECT education, count(*)
FROM USER_DETAILS
GROUP BY education
答案 2 :(得分:0)
您可以这样做:
select sum(case when religion = 'Muslim'
then 1
else 0
end) as muslims,
sum(case when martial_status = 'married'
then 1
else 0
end) as married
...
from your_table
更短的版本是:
select sum(religion = 'Muslim') as muslims,
sum(martial_status = 'married') as married
...
from your_table
答案 3 :(得分:0)
使用没有子查询或类似的单个select
很棘手,但我相信单个查询也应该对您有用。您可以使用单个选择来获取给定列的所有计数,然后使用union all
合并结果,以便单个查询可以获得所有列的所有计数。
select martial_status, count(*) from user_details group by martial_status
union all
select religion, count(*) from user_details group by religion
union all
select education, count(*) from user_details group by education
如果您的表中有NULL
个值,您可能希望省略结果中的值。
如果它确实是你需要的单选,那么你必须改变你的表的布局,但我无法想象这种要求的正当理由。