我正在使用MS SQL server 2012。
我有以下查询
Select HedgeDate, CompanyName, HedgeValue
FROM GasHedges
LEFT OUTER JOIN GasCompanies ON GasHedges.CompanyID = GasCompanies.ID
WHERE HedgeDate BETWEEN '2014-09-01' AND '2014-09-05'
返回
我想以下列格式显示它。
我整个上午一直在努力,并没有真正到达那里。我不想在SQL代码中指定companyName,因为可以将更多公司添加到表中。我一直在尝试不同的连接变体,但没有到达任何地方。我也在看工会,但似乎无法得到它。
非常感谢任何帮助。
答案 0 :(得分:2)
SELECT HedgeDate, CompanyName, HedgeValue
FROM GasHedges
LEFT OUTER JOIN GasCompanies ON GasHedges.CompanyID = GasCompanies.ID
PIVOT (count(HedgeValue) FOR CompanyName in ([RWET], [JPMorgan], [Statoil]))
WHERE HedgeDate BETWEEN '2014-09-01' AND '2014-09-05'
你去吧
编辑1,
如果您希望列表是动态的,请参阅HERE 尝试自己动手以确保理解
答案 1 :(得分:1)
感谢ah_hau,在你的指导下,我得到了以下代码
DECLARE @StartDate date
DECLARE @EndDate date
DECLARE @cols nvarchar(2000)
DECLARE @query nvarchar(3000)
select @cols = coalesce(@cols + ',[' + companyName + ']', '[' + companyName + ']')
from GasCompanies
set @query = 'select *
from
(Select HedgeDate, CompanyName, HedgeValue
FROM GasHedges
LEFT OUTER JOIN GasCompanies ON GasHedges.CompanyID = GasCompanies.ID
WHERE HedgeDate BETWEEN DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0) AND dateadd(month,1+datediff(month,0,getdate()),-1)) as s
PIVOT
(
count(HedgeValue) FOR CompanyName in ( '+@cols +' )
) as t'
execute(@query)