具有计算成本列的所需输出表T
:
SvcID Code ID Date Mins Units Cost 1 3000 15 4/4/2016 60 10 70 2 3000 17 4/4/2016 45 10 0 3 3000 15 5/2/2016 30 10 70 4 3000 18 5/2/2016 60 10 0 5 3000 10 5/2/2016 30 10 0 6 4200 16 2/1/2016 60 4 60 7 4200 9 2/1/2016 30 2 30
查询计算和显示:
SELECT ... ,CASE WHEN Code=4200 THEN Units*15 WHEN Code=3000 THEN ? END AS Cost FROM ... WHERE Code IN ('3000','4200') GROUP BY ....;
对于Code 3000在同一日期提供的所有服务,总成本应为70,无论提供多少服务。此代码的分钟和单位之间没有关系来计算成本。
一种方法是将任何一项服务的成本计算为70,并使剩余服务在同一日期成本为0。可以在CASE
声明中完成吗?
有没有更好的方法来实现这一目标?
答案 0 :(得分:1)
您需要调查窗口函数MSDN。
你的情况会变成这样:
-- New select statament
SELECT
...
,CASE
WHEN Code=4200 THEN Units*15
WHEN Code=3000 THEN ( CASE WHEN DuplicateNum = 1 THEN 70 ELSE 0 END )?
END AS Cost
FROM(
-- Your current query (with case statement removed) and ROW_NUMBER() function added
SELECT
..., ROW_NUMBER() OVER( PARTITION BY Code, Date ORDER BY ID ) AS DuplicateNum
FROM ...
WHERE Code IN ('3000','4200')
GROUP BY ....
) AS YourCurrentQuery;