根据日期范围,我计算每个月的百分比。我遇到的问题是我编写它的方式它给了我输入的整个日期范围的百分比。所以例如每个月将是54%而不是每个月的唯一百分比。我确信有一个简单的解决方案,我只是不知道它是什么。我认为我使它变得比它需要的更复杂。
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, finspectdata), 0) AS 'Date'
,COUNT(*) AS Lots
,sum(flotSize) as 'Lot Size'
,sum(fnumreject) as Rejected
,sum(fsampSize) as 'Sample Size'
,((select cast(count(*) as decimal)
from monthlyinspect
where finspectData < fddue_date
and fddue_date >= '20140101'
and fddue_date <= '20140531') / (select cast(count(*) as decimal)
from monthlyinspect
where fddue_date > '20140101'
and fddue_date < '20140531'))
FROM monthlyinspect
WHERE finspectdata >= '20140101'
AND finspectdata <= '20140531'
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, finspectdata), 0)
Order by 'Date'
输出
Date Lots Lot Size Rejected Sample Size Percent
--------------------------------------------------------------------------------------
2014-01-01 00:00:00.000 916 455358 3082 10835 0.5488603615404768142
2014-02-01 00:00:00.000 692 410567 1114 7870 0.5488603615404768142
2014-03-01 00:00:00.000 694 424251 391 8095 0.5488603615404768142
2014-04-01 00:00:00.000 872 429746 1642 10017 0.5488603615404768142
2014-05-01 00:00:00.000 633 312913 572 7340 0.5488603615404768142
答案 0 :(得分:0)
如果我理解了查询,那么我认为这就是你要做的。
SELECT
DATEADD(MONTH, DATEDIFF(MONTH, 0, finspectdata), 0) AS 'Date'
, COUNT(*) AS Lots
, SUM(flotSize) as 'Lot Size'
, SUM(fnumreject) as Rejected
, SUM(fsampSize) as 'Sample Size'
, SUM(CASE
WHEN finspectdata < fddue_date
AND
fddue_date >= '20140101'
AND
fddue_date <= '20140531'
THEN
1
ELSE
0
END)
/
SUM(CASE
WHEN
fddue_date >= '20140101'
AND
fddue_date <= '20140531'
THEN
1
ELSE
0
END)
FROM
monthlyinspect
WHERE
finspectdata >= '20140101'
AND
finspectdata <= '20140531'
GROUP BY
DATEADD(MONTH, DATEDIFF(MONTH, 0, finspectdata), 0)
ORDER BY
'Date'
希望这会让你朝着正确的方向前进。
或者,我可能会考虑在许多步骤中构建此查询。
在一个数据集中获取组数据,然后在另一个数据集中获取百分比。然后根据日期将两者结合起来。
有了类似的东西,我通常会使用临时表(变量)来处理数据,而我正在处理它。