我有下表: -
我需要计算卡车利用率&最终输出应如下: -
我。利用率(每日): -
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]
如何生成上述输出?
答案 0 :(得分:1)
您可以像这样使用SUM
和COUNT
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'