动态命名列-使用SQL Server 2008

时间:2019-03-20 19:13:31

标签: sql tsql sql-server-2008

我有一个查询,该查询引用了动态calander表,它根据当前日期更新帐龄。我在另一个查询中使用此表,该表的总和是基于过期QTR的销售额。这些值将随着时间的流逝而更新,我可以分配诸如“ AGED1Q”之类的列名,但我想找到一种使用calander表中实际期间名称的方法。任何建议将不胜感激。

下面是当前查询,我添加了一些注释行,我想在这些行中进行更改。再次感谢

    SELECT        dbo.CUSTOMER_ORDER.CUSTOMER_ID AS CUST_ID, 

              SUM(CASE WHEN dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -4 THEN dbo.CUST_ORDER_LINE.TOTAL_AMT_ORDERED ELSE 0 END) AS '-4', --As MAX(dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTR) WHERE dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -4 
              SUM(CASE WHEN dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -3 THEN dbo.CUST_ORDER_LINE.TOTAL_AMT_ORDERED ELSE 0 END) AS '-3', --As MAX(dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTR) WHERE dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -3
              SUM(CASE WHEN dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -2 THEN dbo.CUST_ORDER_LINE.TOTAL_AMT_ORDERED ELSE 0 END) AS '-2', --As MAX(dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTR) WHERE dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -2
              SUM(CASE WHEN dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -1 THEN dbo.CUST_ORDER_LINE.TOTAL_AMT_ORDERED ELSE 0 END) AS '-1', --As MAX(dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTR) WHERE dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -1
              SUM(CASE WHEN dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED IN(-4, -3, -2, -1) THEN dbo.CUST_ORDER_LINE.TOTAL_AMT_ORDERED ELSE 0 END) AS 'TOTAL'

FROM            dbo.CUSTOMER_ORDER LEFT OUTER JOIN
                         dbo.UFC_Calander LEFT OUTER JOIN
                         dbo.UCC_CALENDAR_TODAY_BASED_AGING ON dbo.UFC_Calander.DAY = dbo.UCC_CALENDAR_TODAY_BASED_AGING.DATES ON 
                         dbo.CUSTOMER_ORDER.ORDER_DATE = dbo.UFC_Calander.DAY LEFT OUTER JOIN
                         dbo.CUSTOMER ON dbo.CUSTOMER_ORDER.CUSTOMER_ID = dbo.CUSTOMER.ID RIGHT OUTER JOIN
                         dbo.PART RIGHT OUTER JOIN
                         dbo.CUST_ORDER_LINE ON dbo.PART.ID = dbo.CUST_ORDER_LINE.PART_ID ON dbo.CUSTOMER_ORDER.ID = dbo.CUST_ORDER_LINE.CUST_ORDER_ID

WHERE        (dbo.CUSTOMER_ORDER.STATUS <> 'x') AND dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED IN(-4, -3, -2, -1)

GROUP BY dbo.CUSTOMER_ORDER.CUSTOMER_ID

HAVING        (dbo.CUSTOMER_ORDER.CUSTOMER_ID <> 'UNFOCO') AND (dbo.CUSTOMER_ORDER.CUSTOMER_ID <> 'QUOTE')
ORDER BY TOTAL DESC

0 个答案:

没有答案