我得到了这段代码,在这段代码中我总结了慢速和快速的驱动程序。我的问题是我必须将这笔钱与正常的司机分开。我不知道如何在这个陈述中做一个分工:
Select *
FROM (
Select date as Datetime, tevent.name as Event, level = case
when levelname = 'High' then 'High'
when levelname = 'Normal' then 'Normal'
when shiftname = 'Low' then 'Low'
end, SUM(value) as sum
from tCount inner join tEvent ON tCount.eventid = tevent.id
where Name in ('Drive Fast', 'Drive Slow')
and date > getdate() -1
and tevent.Name in ('E01','E02','E03','E04','E05','E06','E07','E08')
and CalName = 'Drive'
group by tevent.name, date, levelname
) as s
PIVOT
(
SUM(sum)
FOR Event IN (E01,E02,E03,E04,E05,E06,E07,E08)
) as p
order by Datetime, level
然后我将相同的Select语句与普通的驱动程序放在一起:
... from tCount inner join tEvent ON tCount.eventid = tevent.id
where Name in ('drive normal') ...
我想这样做一个部门:
(Sum('drive fast' + 'drive slow')/Sum('drive normal')) * 100
答案 0 :(得分:1)
有一种更简单的方法可以在SQL语句中包含不同总和的不同情况:总结一个案例,如下面的百分比计算:
Select ...
, SUM(case Name
when 'drive fast' then Value
when 'drive slow' then value
else 0 end)
/ SUM(case Name
when 'drive normal' then value
else 0 end) * 100 as percentage
from ...
where ...
group by ...;
由于我缺少测试此代码的数据,因此我在CARS表上创建了一个查询,作为培训材料,实现了相同的原则。
select Cylinders
, sum(case origin when 'USA' then EngineSize
when 'Asia' then EngineSize
else 0.0 end)
/ sum(case origin when 'Europe' then EngineSize
else 0.0 end)
* 100 as percentage
from sasHelp.cars
where Cylinders in (4, 5, 6, 12)
group by Cylinders