>表:tbl_1
列:名称、选项
-> name | option
-> abc_1 | yes
-> abc_2 | no
-> abc_3 | yes
-> abc_1 | no
-> abc_2 | yes
-> abc_3 | no
-> abc_1 | yes
-> abc_2 | no
-> abc_3 | yes
-> abc_1 | yes
-> abc_2 | no
-> abc_3 | yes
现在,我想问的查询...
我怎样才能获得那些有选择的唯一名称:是比否更多?
查询应返回
-> name
-> abc_1
-> abc_3
我尝试了很多查询但没有成功,请帮忙
谢谢。
MySql 将布尔表达式评估为False
和True
的0
或1
,因此不需要IF
或CASE
语句:
select name
from tbl_1
group by name
having sum(`option` = 'yes') > sum(`option` = 'no')
请参阅演示。
结果:
| name |
| ----- |
| abc_1 |
| abc_3 |
返回指定结果的简洁MySQL查询如下所示:
SELECT t.name
FROM tbl_1 t
GROUP
BY t.name
HAVING SUM(IF(t.option = 'yes',1,0)) > SUM(IF(t.option = 'no',1,0))
这是使用一些"条件聚合"速记。
让我们稍微解开一下,以便了解此查询正在执行的操作。请考虑以下查询:
SELECT t.name
, t.option
, IF(t.option = 'yes',1,0) AS option_yes
, IF(t.option = 'no' ,1,0) AS option_no
FROM tbl_1 t
ORDER
BY t.name
SELECT 列表中的表达式针对每一行计算,IF(( 函数的计算结果为 1 或 0。
现在考虑当聚合这些表达式时会发生什么,将所有 1 和 0 相加
SELECT t.name
, t.option
, SUM( IF(t.option = 'yes',1,0) ) AS cnt_option_yes
, SUM( IF(t.option = 'no' ,1,0) ) AS cnt_option_no
FROM tbl_1 t
GROUP
BY t.name
, t.option
现在将"选项"排除在分组 by 子句之外,并对两个聚合进行比较。
SELECT t.name
, SUM( IF(t.option = 'yes',1,0) ) AS cnt_option_yes
, SUM( IF(t.option = 'no' ,1,0) ) AS cnt_option_no
, SUM(IF(t.option='yes',1,0) ) > SUM(IF(t.option='no',1,0)) AS _compare
FROM tbl_1 t
GROUP
BY t.name
可以在HAVING
子句中对聚合进行比较。这会产生这个答案开头的查询。
您可以尝试条件和
select name
, sum( case when `option` ='yes' then 1 else 0 end) num_yes
, sum( case when `option` ='no' then 1 else 0 end) num_no
from my_table
group by name
order by num_yes desc, num_no desc
条件聚合 -
select
name,
count (case when `option` = 'yes' then 1 else null end) as y,
count (case when `option` <> 'yes' then 1 else null end) as n
from
tbl_1
group by
`name`
having count (case when `option` = 'yes' then 1 else null end) > count (case when `option` <> 'yes' then 1 else null end)
小提琴