嘿伙计们,我试图将此查询转换为数据透视表,我已经搜索了所有地方,但似乎无法应用它。以下是我的代码。
SELECT ClientPartner, ClientManager, WIPAmount
FROM tblTranWIP
WHERE (WIPDate>={ts '2013-04-01 00:00:00'}
AND WIPDate<{ts '2014-03-31 00:00:01'})AND TransTypeIndex=1 AND ContIndex<900000
以下屏幕截图显示了我的输出。我基本上希望将经理和合作伙伴作为第一列和第一行,然后将WipAmount放在中间,因为ClientPartners和Managers匹配id。屏幕截图显示它比我解释的更容易。链接是截图,系统不允许我添加嵌入图像
答案 0 :(得分:1)
我至少有一种方法可以获得您正在寻找的信息,那就是使用PIVOT:
SELECT pvt.*
FROM
(
SELECT ClientPartner, ClientManager, WIPAmount FROM tblTranWIP
) AS tranwip
PIVOT
(
SUM(WIPAmount) FOR ClientPartner IN ([46], [58], [177], [207])
) AS pvt
这是SQL Fiddle。
答案 1 :(得分:0)
DECLARE @sql varchar(MAX)
DECLARE @columns TABLE (COL varchar(50))
declare @columnscsv varchar(MAX)
insert into @columns
select distinct ClientPartner from tblTranWip
select @columnscsv = COALESCE(@columnscsv + '],[','') + COL from @columns
set @columnscsv = '[' + @columnscsv + ']'
SET @sql = 'Select ClientManager ' + @columnscsv + ' FROM(SELECT ClientPartner, ClientManager, WipAmount FROM tblTranWip) a
PIVOT (MAX(WipAmount) for ClientPartner in (' + @columnscsv + ')) AS PVT ORDER by ClientManager'
EXEC (@sql)