2

我有近 18 个选择联合,每个选择包含几乎 10 个相同的条件,只有一个条件不同。请查看下面的 sql 结构。

SELECT count(*) AS count, 'blue' as title 
FROM Users
WHERE [a long list of conditions,which are identical] AND eyes='blue'

UNION

SELECT count(*) AS count, 'hazel' as title 
FROM Users
WHERE [a long list of conditions,which are identical] AND eyes='hazel'

UNION

SELECT count(*) AS count, 'Black' as title 
FROM Users
WHERE [a long list of conditions,which are identical] AND eyes='black'

等等。

检索此类数据的更好方法是什么。有更好的主意吗?

编辑:

很抱歉之前没有提到这一点,这些条件不是基于单个字段“眼睛”,它可以是不同的,例如头发、身高等,因此不能按照建议使用 group by。

4

3 回答 3

4

你想要条件总和:

select count(*),
       sum(case when eyes = 'blue' then 1 else 0 end) as blue,
       sum(case when eyes = 'hazel' then 1 else - end) as hazel,
       . . . 
from users
where <long list of conditions>

这会将所有内容放在一行中。要将所有内容放在单独的行上,您可能需要:

select eyes, count(*)
from users
where <long list of conditions>
group by eyes

这将为您提供每种眼睛颜色的单独行。

根据您的评论,最好的方法可能是在一行上进行汇总,然后取消透视值。不幸的是,MySQL 没有 unpivot,所以以下虽然丑陋但应该是有效的:

select titles.title,
       max(case when titles.title= 'blue' then blue
                when titles.title = 'hazel' then hazel
                . . .
           end) as cnt
from (select count(*) as cnt,
             sum(case when eyes = 'blue' then 1 else 0 end) as blue,
             sum(case when eyes = 'hazel' then 1 else - end) as hazel,
             . . . 
      from users
      where <long list of conditionss
     ) cross join
     (select 'blue' as title union all
      select 'hazel' union all
      . . .
     ) titles
group by titles.title
于 2012-12-10T20:31:29.833 回答
2

虽然这与您上面的输出不完全相同,但是

select eyes, count(*)
from Users
where [a long list of conditions,which are identical]
group by eyes

应该给你你想要的信息。

于 2012-12-10T20:32:05.670 回答
0

if you are trying to get the number of users for each eyes color you should try :

SELECT count( * ) AS c, 'eye'
FROM Users
WHERE .... all your conditions here ...
GROUP BY 'eye'
于 2012-12-10T20:39:13.167 回答