我有一个3列的表格。 DateRangeFields,IsOutOfTarget和AmountOfJobs。
我需要的是按DateRangeFields对结果进行分组,并显示在该日期范围内超出目标的作业百分比。数据如下所示
我试图创建一个显示数据的表,但是Stackoverflow似乎不允许这样做,所以我在Dbfiddle中创建了它。
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=ae9ce68d96f0d88a3f78ad6987010f56
答案 0 :(得分:1)
只需使用条件聚合:
Select DateRangeFields,
(SUM(CASE WHEN IsOutOfTarget = 'True' THEN AmountOfJobs END) * 1.0 /
SUM(AmountOfJobs)
) as ratio
From @MyTable t
Group By DateRangeFields;
答案 1 :(得分:0)
也许不是最干净的方法,但是:
Select A.DateRangeFields, CAST(OutOfTargetJobs AS FLOAT)/CAST(OutOfTargetJobs+InTargetJobs AS FLOAT) As Percentage FROM (
Select DateRangeFields, SUM(AmountOfJobs) AS OutOfTargetJobs
From @MyTable
Where IsOutOfTarget = 'True'
Group By DateRangeFields, IsOutOfTarget
) A
Inner Join
(
Select DateRangeFields, SUM(AmountOfJobs) AS InTargetJobs From @MyTable
Where IsOutOfTarget = 'False'
Group By DateRangeFields, IsOutOfTarget
) B on A.DateRangeFields = B.DateRangeFields;
答案 2 :(得分:0)
怎么样:
select sum(c1) as s_c1, sum(c2) as s_c2, divide(s_c1, s_c2) as pct from tab group by c3;
divide
是您可以在正式文档中找到的功能。我不确定。
对我而言,不接触SQL的时间很长。所以您知道,我上面提供的语句可能无法运行。