1

我有带有以下列的 users_details 表

martial_status | religion | education 

我想从下表中获取值的计数,如下所示。

married (100)
single (200)
Muslim(50)
Jews (50)
Christian(50)
Graduates(100) 
etc, etc. 

我不知道是否可以使用单个 SELECT 获得所有计数,请帮助。

4

4 回答 4

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` )
于 2012-06-25T09:12:38.963 回答
1

您需要分别处理每一列,然后合并它-

  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
于 2012-06-25T09:13:58.173 回答
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
于 2012-06-25T09:11:10.530 回答
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的表中有值,您可能希望从结果中省略这些值。

如果它确实是您需要的单个选择,那么您将不得不更改表格的布局,但我无法想象这种要求的正当理由。

于 2012-06-25T09:20:02.287 回答