我设法建立了一个很好的小T-SQL语句,将调度信息转化为每月列。
SELECT *
FROM
(
SELECT
t1.customer_code,
t1.part_number,
LEFT(DATENAME(month, [formatted_date]),3) as [Month],
t1.quantity as [quantity] FROM FORECAST_VIEW as t1
where
quantity <> 0
and formatted_date >= DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
) as p
pivot
(
sum(quantity)
for [Month] in (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec)
) as p
order by customer_code, part_number
这将生成带
列的输出customer_code, part_number, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
并将每个月所需的part_number数量相加。
这样可以正常工作并在报告中创造奇迹但是如果我可以让月份列从当月开始并按顺序进行12个月,那么这将是锦上添花。
问题是我不知道该怎么做。
如果我今天运行它,输出将是
customer_code, part_number, Nov, Dec, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct
有没有人有任何提示?
由于
EDIT 我刚才想到的一件事,如果我找不到解决方案,我就不会排除它的丑陋。 我可以将整个T-SQL语句放在IF块中
IF LEFT(DATENAME(month, GETDATE()),3) = 'Nov'
BEGIN
SELECT *
FROM
(
...
) as p
pivot
( sum(quantity)
for [Month] in (Nov, Dec, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct)
) as p
order by customer_code, part_number
END
并做12次并调整数月。