SQL计算多列的值

时间:2015-10-06 11:29:12

标签: sql

我有一张桌子,上面有这样的栏目:

NAME1,NAME2 name_thesame,adress1,adress2,adress_thesame,city1,城2,city_thesame

在以_thesame结尾的所有列中,如果name1和name2相同,与adress等相同,则为true或false。

我现在需要一个查询,它返回每个_thesame列有多少真和假的计数。

不能围绕如何进行此查询 - 任何团体都有一些想法或指针?感谢

2 个答案:

答案 0 :(得分:2)

对于单个属性,您可以执行以下操作:

select name_thesame, count(*) 
from table
group by name_thesame

这将为您提供如下结果:

 true     10
 false    15

如果您希望将其作为多列的列表,则可以将查询联合起来:

select 'Name', name_thesame, count(*) 
  from table
  group by name_thesame
union 
select 'Address', adress_thesame, count(*) 
  from table
  group by adress_thesame

得到:

 Name    true   10
 Name    false  15
 Address true   20
 Address false  5

答案 1 :(得分:2)

这是另一种选择:

SELECT SUM(CASE WHEN name_thesame = true THEN 1 ELSE 0 END) as nametrue,
       SUM(CASE WHEN name_thesame = false THEN 1 ELSE 0 END) as namefalse,
       SUM(CASE WHEN adress_thesame = true THEN 1 ELSE 0 END) as adresstrue,
       SUM(CASE WHEN adress_thesame = false THEN 1 ELSE 0 END) as adressfalse,
       SUM(CASE WHEN city_thesame = true THEN 1 ELSE 0 END) as citytrue,
       SUM(CASE WHEN city_thesame = false THEN 1 ELSE 0 END) as cityfalse
FROM yourTable

如果相关,您可以调整它以处理NULL

...
CASE WHEN name_thesame = false OR name_thesame IS NULL THEN 1 ELSE 0 END
...

NVL()ISNULL()IFNULL()COALESCE(),具体取决于您使用的DBMS(语法始终相同):

...
CASE WHEN COALESCE(name_thesame, false) = false THEN 1 ELSE 0 END
...

结果:

nametrue | namefalse | adresstrue | adressfalse | citytrue | cityfalse
       5 |         7 |          2 |           1 |       10 |         8