我正在查询一年中一个人拼车的次数,按季度细分。每次这个人拼车20次,他们就有资格获得报酬。拼车数量全年继续累计,但每季度只支付一次。
我有这样的数据:
+-------+-----+--------+----+
|quarter|value|RunTotal|Paid|
+-------+-----+--------+----+
|Jan-Mar|19.0 |19.0 |0.00|
+-------+-----+--------+----+
|Apr-Jun|2.0 |21.0 |1.00|
+-------+-----+--------+----+
|Jul-Sep|0.0 |21.0 |0.00|
+-------+-----+--------+----+
|Oct-Dec|0.0 |21.0 |0.00|
+-------+-----+--------+----+
如图所示,他们在第一季度没有得到支票。然而,他们在第二次做到了。我可以计算出总的罚款。但是,我需要在付费列中执行总计,减去之前的任何支出。请看一下,给我一些帮助。
DECLARE @SalesTbl TABLE (quarter varchar(250), value decimal(18,1), RunningTotal decimal(18,1), earned money)
DECLARE @RunningTotal decimal(18,1), @earned money
SET @RunningTotal = 0
SET @earned = 0
INSERT INTO @SalesTbl
SELECT CASE DatePart(q, c.date)
WHEN 1 THEN 'Jan-Mar'
WHEN 2 THEN 'Apr-Jun'
WHEN 3 THEN 'Jul-Sep'
WHEN 4 THEN 'Oct-Dec' END AS quarter,
IsNULL(Sum(t.value),0) AS value,
null,
0
FROM @calendar c
LEFT OUTER JOIN events e ON (DatePart(q, c.date) = DatePart(q, e.eventDate) AND e.employeeID = @employeeID AND e.eventType = 'CP' AND Year(eventDate) = @year)
LEFT JOIN types t ON t.typeID = e.eventType
GROUP BY DatePart(q, c.date)
UPDATE @SalesTbl
SET @RunningTotal = RunningTotal = @RunningTotal + value, @earned = earned = Floor(@RunningTotal/20) - (SELECT Sum(earned) FROM @SalesTbl)
FROM @SalesTbl
SELECT * FROM @SalesTbl
答案 0 :(得分:0)
听起来你应该使用SQL窗口
有关示例,请参阅以下页面: http://technet.microsoft.com/en-us/library/ms189461.aspx
您应该按季度(DatePart(q,c.date))和SUM(t.value)进行分区。 SUM(SUM(t.value))OVER(PARTITION BY DatePart(q,c.date))AS'Total'