我有以下计数
SELECT (SUM(CASE WHEN DeliveryCode = 2 THEN 1
WHEN Customer_id <> Customer_id THEN 1
ELSE 0
END) AS col
尝试按日期顺序进行计数,
日期1
如果客户未能提取包裹,则为1,如果不是0
日期2
如果他们失败了,请在下一个日期再做一次,然后是1,
日期3
如果他们在下一个日期,设法拿起包裹,那么对于该客户ID,count将返回0。
我上面的工作差不多了,但是当客户
时,总不能回到0但我还想做点数,如果客户拿起他们的包裹计数到0,但如果他们开始未能再次拿起他们的包裹,在未来的日期,它会再次开始积累1 < / p>
Customer_id DATE DeliveryCode
1 01/01/2017 2
1 02/01/2017 2
1 03/01/2017 2
2 01/01/2017 1
3 01/01/2017 1
3 02/01/2017 1
4 01/01/2017 2
4 02/01/2017 2
4 03/01/2017 1
ID 1 will equal 3
ID 2 will equal 0
ID 3 will equal 0
ID 4 will equal 0
请提出任何想法
答案 0 :(得分:0)
如果我们可以假设交货尝试在成功后停止(1)那么我们可以查找客户的最大日期然后使用它和它的交货代码来检查我们是否需要重置为0
RexTester Tested :(注意@params未在rex测试中定义,因为问题范围已更改)
SELECT A.Customer_ID
, sum(case A.deliveryCode when 2 then 1 else 0 end) *
min(Case when A.mDate = MaxDel.MDate and DeliveryCode <> 2 then 0 else 1 end)
as ActiveConcurrentFailedDelivery
FROM SO50411005 A
LEFT JOIN (SELECT Customer_ID, max(mDate) mDate
FROM SO50411005
GROUP BY Customer_ID) MaxDel
on A.Customer_ID = MaxDel.Customer_ID
WHERE A.mDate between @paramStart and @ParamEnd
GROUP BY A.CUSTOMER_ID
结果:
+----+-------------+--------------------------------+
| | Customer_ID | ActiveConcurrentFailedDelivery |
+----+-------------+--------------------------------+
| 1 | 1 | 3 |
| 2 | 2 | 0 |
| 3 | 3 | 0 |
| 4 | 4 | 0 |
+----+-------------+--------------------------------+