SQL PIVOT两个表

时间:2017-12-26 08:08:04

标签: sql pivot

我正在尝试为工作排序,我可以从每个仓库获得数量某个产品系列。我正在使用SAP B1软件

SELECT T0.[ItemCode], [01],[BNE],[SHOP],[Transit]
    FROM OITM T0 INNER JOIN OITW T1 ON T0.[ItemCode] = T1.[ItemCode]
    PIVOT(SUM(T1.OnHand) FOR T1.WhsCode IN([01],[BNE],[SHOP],[Transit])) AS PivotTable
    Group By T0.[ItemCode]

无论我尝试调整解决问题的方法,我都会收到更多的错误代码,比如类似的类型或绑定的错误......我想这很明显,但任何人都可以帮忙吗?

数据如下所示:(有几百个产品系列)

Product Code    Warehouse    Quantity
PROD0001          01            50 
                  BNE           94   
                  Shop          80   
                  Transit       80 
-------------------------------------    
PROD0002          01            10  
                  BNE           20   
                  Shop          00   
                  Transit       70
-------------------------------------  
PROD0003          01            99  
                  BNE           62   
                  Shop          20   
                  Transit       15   

我想通过SQL查询实现这样的目标:

Product Code    01   BNE   Shop   Transit  
PROD0001        50   94    80     80 
PROD0002        10   20    00     70
PROD0003        99   62    20     15

1 个答案:

答案 0 :(得分:0)

创建表格

create table demo
(
   productcode nvarchar(50),
   Warehouse nvarchar(50),
   Quantity int
);

插入表格

insert into demo values

('PROD0001','01','50'),
('PROD0001','BNE','94'),
('PROD0001','Shop','80'),
('PROD0001','Transit','80'),
('PROD0002','01','10'),
('PROD0002','BNE','20'),
('PROD0002','Shop','00'),
('PROD0002','Transit','70'),
('PROD0003','01','99'),
('PROD0003','BNE','62'),
('PROD0003','Shop','20'),
('PROD0003','Transit','15');

SQL查询:

declare @sql as varchar(max);

select @sql = 'select [productcode], ' + stuff((
    select distinct ',sum(case [WareHouse] when ' + char(39) + [WareHouse] + char(39) + ' then cast([Quantity] as float) end) as [' + [WareHouse] + ']'
    from demo
    for xml path('')
)
, 1, 1, ''
);

select @sql += ' from [demo] group by [productcode];';

exec(@sql);