使用IF-ELSE进行SQL计数

时间:2013-06-25 10:30:31

标签: sql

我正在尝试编写一个SQL命令,可以按人员存储表设备历史记录。当前设备不是null devicex_mac。因此,device2_mac可能是当前设备(device3_mac为null)或device1_max可能是当前设备(device2_mac和device3_mac都为空)。

**Person Table**            
id  device1_mac device2_mac device3_mac


**Device Table**        
mac   brand   model

根据上述事实,我如何检测当前设备并加入两个表以获得以下结果。

**RESULT:**

BRAND   MODEL   COUNT
BRAND1  Model1  350000
BRAND1  Model2  700000
BRAND2  Model1  480000

2 个答案:

答案 0 :(得分:3)

如果您想查看所有列的分布,您可以这样做:

select d.brand, d.model, count(*)
from ((select id, device1_mac as mac
       from person
      ) union all
      (select id, device2_mac
       from person
      ) union all
      (select id, device3_mac
       from person
      )
     ) pd left outer join
     devices d
     on pd.mac = d.mac
where mac is not null
group by d.brand, d.model

如果最后一列包含您想要的信息,您可以这样做:

select d.brand, d.model, count(*)
from person p left outer join
     devices d
     on coalesce(p.device3_mac, p.device2_mac, p.device1_mac) = d.mac
where mac is not null
group by d.brand, d.model

coalesce()选择第一个非NULL值。

编辑:

如果问题是关于效果devices(mac)上有一个索引,那么我会建议第一个查询的变体:

select d.brand, d.model, count(*)
from ((select id, device1_mac as mac
       from person
       where device2_mac is null and device1_mac is not null
      ) union all
      (select id, device2_mac
       from person
       where device3_mac is null and device2_mac is not null
      ) union all
      (select id, device3_mac
       from person
       where device3_mac is not null
      )
     ) pd left outer join
     devices d
     on pd.mac = d.mac
where mac is not null
group by d.brand, d.model

or子句中使用函数或on通常会导致数据库忽略索引。

答案 1 :(得分:1)

我假设任何时候只有一个设备列有值。然后你可以这样做:

SELECT
   brand,
   model,
   COUNT(*)
FROM
  tblDevice 
  JOIN tblPerson ON
     tblDevice.mac = tblPerson.device1_mac OR
     tblDevice.mac = tblPerson.device2_mac OR
     tblDevice.mac = tblPerson.device3_mac
group by 
   brand, 
   model