SQL查询按计数和左联接表分组

时间:2018-08-14 07:33:13

标签: sql-server tsql

我需要您的帮助!我掌握了一些简单的SQL技能,但是此查询使我丧命...

我的桌子

enter image description here

现在我想要设备上的TOP5工作时间(什么设备具有最长的工作时间)。

我想要这个输出:

enter image description here

我的查询:

SELECT
   Equipment, EquipmentName, count(Equipment) as Count
FROM
   Operations o
   LEFT JOIN Orders ord ON  ord.Id = o.[Order]
   LEFT OUTER JOIN Equipments e ON ord.Equipment = e.EquipmentNumber
GROUP BY 
   Equipment, EquipmentName
   ORDER BY Count DESC;

另一个问题是如何显示o.Worktime? 我在GroupBy上遇到了一个错误...

请帮助我,谢谢!

2 个答案:

答案 0 :(得分:1)

您可以尝试以下查询:

select equip_nr,
       (select equipmentname from table_equipments where equipmentnr = [to].equip_nr) equip_name,
       sum(timeInMins) / 60.0 Worktime
from (
    select (select equipmentnr from table_orders where id = [to].[order]) equip_nr,
           case when workunittime = 'RH' then worktime * 60 else worktime end timeInMins
    from table_operations [to]
    where exists(select 1 from table_orders
                 where [to].[order] = id
                   and location = '152')
      and [start] >= '2018-07-01 00:00:00.000' and [start] < '2018-08-01 00:00:00.000'
) [to] group by equip_nr

顺便说一下,LEFT JOIN等同于LEFT OUTER JOIN

答案 1 :(得分:1)

只需将SUM(worktime)用作聚合函数,而不要使用COUNT(Equipment)

SELECT
   e.[ID_Equipment]
   , Name
   , SUM( IIF(o.WorkUnitTime='MIN', worktime/60.0, worktime) ) as WorktimeMIN
FROM
   Operations o
   LEFT JOIN Orders ord ON  ord.ID_Order = o.ID_Order
   LEFT OUTER JOIN Equipment e ON ord.ID_Equipment = e.ID_Equipment
GROUP BY 
   e.[ID_Equipment]
   , Name
ORDER BY
  WorktimeMIN DESC

在此处查看SQL Fiddle:http://sqlfiddle.com/#!18/5b5ed/11