-1

我正在使用下面的代码,它没有给我。每个月的订单

但我想在每个月的列中填入订单号。

参考号 派对名称 物品名称
订单 1 供应商 1 项目 A
订单 2 供应商 1 B项
订单 3 供应商 2 B项
订单 4 供应商 3 项目 C
订单 5 七月 供应商 4 项目 C

我需要的输出

物品名称 二月 三月 四月 可能 七月
项目 A 订单1
B项 订单 2,订单 3
项目 C 订单 4 订单5
SELECT *
FROM (SELECT [Name Of Item], 
       DATENAME(MONTH, OrderDate) [Month],
       Count(1)[Ord Ref]
      FROM Stock_Master_Pur_Ord_Del
      GROUP BY [Name Of Item], 
      DATENAME(MONTH, OrderDate)) AS MontlySalesData
PIVOT(sum([Ord Ref])
    FOR Month IN ([January],[February],[March],[April],[May],
    [June],[July],[August],[September],[October],[November],
    [December]) )AS MNamePivot
4

1 回答 1

1

较新版本的 SQL Server(我的意思是四年了)支持string_agg(). 您可以使用条件聚合:

select name_of_item,
       string_agg(case when month = 'Jan' then ord_ref end) within group (order by ord_ref) as jan,
       string_agg(case when month = 'Feb' then ord_ref end) within group (order by ord_ref) as feb,
       string_agg(case when month = 'Mar' then ord_ref end) within group (order by ord_ref) as mar,
       string_agg(case when month = 'Apr' then ord_ref end) within group (order by ord_ref) as apr,
       string_agg(case when month = 'May' then ord_ref end) within group (order by ord_ref) as may,
       string_agg(case when month = 'Jun' then ord_ref end) within group (order by ord_ref) as jun,
       string_agg(case when month = 'Jul' then ord_ref end) within group (order by ord_ref) as jul
from Stock_Master_Pur_Ord_Del
group by name_of_item;
于 2021-06-27T11:33:59.663 回答