如下所示,如果campaignIds 相等,我想让它们分组。但我不知道该怎么做。按 CampaignId 分组不起作用。
问问题
54 次
2 回答
2
它应该得到每个费率数字的评级总和吗?您可以通过使用Group By
CampaignID 和SUM()
函数来做到这一点。
select CampaignId,
sum(case when RateNumber = 1 then RateValue else null end) as Rate1,
sum(case when RateNumber = 2 then RateValue else null end) as Rate2,
sum(case when RateNumber = 3 then RateValue else null end) as Rate3,
sum(case when RateNumber = 4 then RateValue else null end) as Rate4,
sum(case when RateNumber = 5 then RateValue else null end) as Rate5,
sum(case when RateNumber = 6 then RateValue else null end) as Rate6,
sum(case when RateNumber = 7 then RateValue else null end) as Rate7,
sum(case when RateNumber = 8 then RateValue else null end) as Rate8,
sum(case when RateNumber = 9 then RateValue else null end) as Rate9,
sum(case when RateNumber = 10 then RateValue else null end) as Rate10,
sum(case when RateNumber = 11 then RateValue else null end) as Rate11,
sum(case when RateNumber = 12 then RateValue else null end) as Rate12,
sum(case when RateNumber = 13 then RateValue else null end) as Rate13,
sum(case when RateNumber = 14 then RateValue else null end) as Rate14,
sum(case when RateNumber = 15 then RateValue else null end) as Rate15,
sum(case when RateNumber = 16 then RateValue else null end) as Rate16,
sum(case when RateNumber = 17 then RateValue else null end) as Rate17,
sum(case when RateNumber = 18 then RateValue else null end) as Rate18,
sum(case when RateNumber = 19 then RateValue else null end) as Rate19,
sum(case when RateNumber = 20 then RateValue else null end) as Rate20,
sum(case when RateNumber = 21 then RateValue else null end) as Rate21,
sum(case when RateNumber = 22 then RateValue else null end) as Rate22,
sum(case when RateNumber = 23 then RateValue else null end) as Rate23,
sum(case when RateNumber = 24 then RateValue else null end) as Rate24
from CampaignRate
group by CampaignId;
看看小提琴。
于 2013-02-21T09:12:49.050 回答
1
研究在 SQL Server 中使用数据透视功能,它可能会产生更具可读性的 SQL http://msdn.microsoft.com/en-gb/library/ms177410(v=sql.105).aspx
SELECT CampaignId, [1] AS Rate1, [2] AS Rate2, [3] AS Rate3
FROM
(SELECT CampaignId, RateNumber, RateValue
FROM CampaignRate) p
PIVOT
(
SUM (RateValue)
FOR RateNumber IN
( [1], [2], [3] )
) AS pvt
ORDER BY pvt.CampaignId;
GO
于 2013-02-21T10:27:00.630 回答