删除了我的原始问题,因为不确定它是否清楚,并认为新的方法可能是最好的前进方式。
我有一张表格,其中包含我们收到的付款详情。我们称之为tblPayments,它的设置类似于(示例)
DatePayment | AccountNo | value | TransactionNo
26/05/2014 | 123456 | 5.99 | 5845878987
26/06/2014 | 123456 | 5.99 | 5845879585
我的任务是在累积的基础上创建破损报告,其标准是错过2次付款,因为它被归类为破损。
示例:帐户123456每月支付5.99。他在2014年6月付款,但之后没有在7月或8月付款,这使得8月份破损并继续支付到12月份,这意味着它将在12月份之前累积破损。
以前用于计算破损的查询是使用EXCEPT
语句完成的,该语句在没有所需的累积数字时完全符合要求。会发布我使用的查询,但它很长,并且之前的问题已经理解了它的逻辑。因此,前进思考一种新的非常可能的智能方式来获取数据。
所需的输出是:
MonthBreakage | AccountNo | BreakageValue
01-Aug-2014 | 123456 | 5.99
01-Sep-2014 | 123456 | 5.99
01-Oct-2014 | 123456 | 5.99
01-Nov-2014 | 123456 | 5.99
01-Dec-2014 | NULL | NULL
空值只是为了突出显示记录不再是破损。
有任何问题请告诉我,我希望已经足够清楚/
答案 0 :(得分:0)
我没有给你一个完整的答案,但我没有时间,所以这就是我到目前为止所做的:
with months as (
select 1 as mkey
union
select 2
union
select 3
union
select 4
union
select 5
union
select 6
union
select 7
union
select 8
union
select 9
union
select 10
union
select 11
union
select 12
)
select mkey, cast('2014-'+cast(mkey as varchar)+'-01' as date) as MonthBreakage, p.*
from months left outer join tblPayments as p on mkey = month(DatePayment)
where mkey > (select max(month(DatePayment)) from tblPayments)
你可以看到它working in a fiddle here。 希望这会有所帮助。
答案 1 :(得分:0)
我只是在两个推文中找到了@Turophile给出的回答中的一个。
由于工会必须对重复进行排序和挑选(即使没有任何重复,也必须检查),因此在月份cte中使用union all而不是union。
或...返工几个月
with months as (
select 1 as mkey
union all
select mkey + 1
from months
where mkey < 12
)