基于类似的定义sql server自动生成新列

时间:2014-02-13 17:40:16

标签: sql-server

我有一个查询,我需要在不同的时间点获取相同指标的列,所以我需要编写如下内容:

select customer,

sum([Is NonRecurring Sale]+[Is NonRecurring Refund]+[Is NonRecurring Chargeback]) as net_report_bill_through,
    sum([net sales]) as report_revenue,
    MIN(transactiontimestamp) as report_date_min,
    MAX(transactiontimestamp) as report_date_max,

    SUM(case when transactiondatestamp >= billthrough_date and transactiondatestamp <= dateadd(day,5,billthrough_date) then ([Is NonRecurring Sale]+[Is NonRecurring Refund]+[Is NonRecurring Chargeback])
                    else 0 end) as g1_num_reports,
    SUM(case when transactiondatestamp >= billthrough_date and transactiondatestamp <= dateadd(day,10,billthrough_date) then ([Is NonRecurring Sale]+[Is NonRecurring Refund]+[Is NonRecurring Chargeback])
                    else 0 end) as g2_num_reports,
    SUM(case when transactiondatestamp >= billthrough_date and transactiondatestamp <= dateadd(day,15,billthrough_date) then ([Is NonRecurring Sale]+[Is NonRecurring Refund]+[Is NonRecurring Chargeback])
                    else 0 end) as g3_num_reports,
    SUM(case when transactiondatestamp >= billthrough_date and transactiondatestamp <= dateadd(day,20,billthrough_date) then ([Is NonRecurring Sale]+[Is NonRecurring Refund]+[Is NonRecurring Chargeback])
                    else 0 end) as g4_num_reports
into #report_info
from #report_transactions
group by customer
order by customer

所以聚合列g1_num_reports, g2_num_reports, g3_num_reports, g4_num_reports它们都是相似的,唯一的区别是dateadd函数的天数,每个函数的天数从5,10,15增加到20,间隔为5.

但是我可能需要更多类似的列,每列的天数增加5。

是否有一种简单的方法来简化这些任务,因此我只需指定我想要的列数,它们就可以自动生成?

0 个答案:

没有答案