我正在尝试执行单个查询来执行我已经拥有的两个查询的工作。让我解释一下。
查询1
select count(*) as equal, someField from table where field1 = field2 group by someField;
查询1的结果
-----------------
|equal|someField|
-----------------
| 90 | some1 |
| 45 | some2 |
-----------------
查询2
select count(*) as different, someField from table where field1 != field2 group by someField;
请注意!=
,这是与Query 1
(以及计数过程中的别名)的唯一区别。
查询2的结果
---------------------
|different|someField|
---------------------
| 10 | some1 |
| 55 | some2 |
---------------------
所以我最终得到了两个结果,但在单个查询中获得相同的数据会很好。
预期结果
---------------------------
|equal|different|someField|
---------------------------
| 90 | 10 | some1 |
| 45 | 55 | some2 |
---------------------------
我通常会尝试很多事情,直到找到预期的结果,但在这里我不知道如何开始。
修改
我会尝试@Rahul回答并得到这个结果:
select
count(case when field1 = field2 then 1 else 0 end) as equal,
count(case when field1 != field2 then 1 else 0 end) as different,
someField
from table
group by someField;
---------------------------
|equal|different|someField|
---------------------------
| 100 | 100 | some1 |
| 100 | 100 | some2 |
---------------------------
答案 0 :(得分:3)
使用CASE
语句来实现相同的目标,如下所示
select
sum(case when field1 = field2 then 1 else 0 end) as equal,
sum(case when field1 != field2 then 1 else 0 end) as different,
someField
from table
group by someField;