使用SQL计算利用率

时间:2017-06-19 03:23:18

标签: sql sql-server

我有下表: -

enter image description here

我需要计算卡车利用率&最终输出应如下: -

我。利用率(每日): -

enter image description here

II。 5月1日至5月3日的平均利用率:44.4% [(33.3%+ 33.3%+ 66.7%)/ 3]

III。 5月1日至5月6日的平均利用率:55.6% [(33.3%+ 33.3%+ 66.7%+ 66.7%+ 66.7%+ 66.7%)/ 6]

如何生成上述输出?

1 个答案:

答案 0 :(得分:1)

您可以像这样使用SUMCOUNT

DECLARE @SampleDAta AS TABLE
(
    Truck varchar(10),
    Status varchar(10),
    Date date 
)
INSERT INTO @SampleDAta
(
    Truck,
    Status,
    [Date]
)
VALUES
('A', 'OFF', '2017-05-01'),
('A', 'OFF', '2017-05-02'),
('A', 'OFF', '2017-05-03'),
('A', 'OFF', '2017-05-04'),
('A', 'OFF', '2017-05-05'),
('A', 'OFF', '2017-05-06'),
('B', 'ON', '2017-05-01'),
('B', 'ON', '2017-05-02'),
('B', 'ON', '2017-05-03'),
('B', 'ON', '2017-05-04'),
('B', 'ON', '2017-05-05'),
('B', 'ON', '2017-05-06'),
('C', 'OFF', '2017-05-01'),
('C', 'OFF', '2017-05-02'),
('C', 'ON', '2017-05-03'),
('C', 'ON', '2017-05-04'),
('C', 'ON', '2017-05-05'),
('C', 'ON', '2017-05-06')

-- I.
SELECT sd.[Date], 
      CAST(100.00 * SUM(CASE WHEN sd.Status = 'ON' THEN 1 ELSE 0 END)/ COUNT(sd.Truck)  AS decimal(10,2)) AS [Utilisation Rate]  
FROM @SampleDAta sd
GROUP BY sd.[Date]

-- II.
;WITH temp AS 
(
    SELECT sd.[Date], 
      CAST(100.00 * SUM(CASE WHEN sd.Status = 'ON' THEN 1 ELSE 0 END)/ COUNT(sd.Truck)  AS decimal(10,2)) AS [Utilisation Rate]  
    FROM @SampleDAta sd
    GROUP BY sd.[Date]

)
SELECT  
      CAST(SUM(t.[Utilisation Rate])/ COUNT(*) AS decimal(10,2)) AS [Utilisation Rate]  
FROM temp t
WHERE t.[Date] BETWEEN '2017-05-01' AND '2017-05-03'

-- III.
;WITH temp AS 
(
    SELECT sd.[Date], 
      CAST(100.00 * SUM(CASE WHEN sd.Status = 'ON' THEN 1 ELSE 0 END)/ COUNT(sd.Truck)  AS decimal(10,2)) AS [Utilisation Rate]  
    FROM @SampleDAta sd
    GROUP BY sd.[Date]

)
SELECT  
      CAST(SUM(t.[Utilisation Rate])/ COUNT(*) AS decimal(10,2)) AS [Utilisation Rate]  
FROM temp t
WHERE t.[Date] BETWEEN '2017-05-01' AND '2017-05-06'

演示链接:http://rextester.com/EQIU21411