我的视图表看起来像这样:
我开始创建一个视图,按每种货币的状态汇总:
WITH C AS (SELECT * FROM CampaignsPublisherReportSummary)
SELECT
'Total' T,
SUM(CASE WHEN PayCurrency='USD' THEN Total END) USD,
SUM(CASE WHEN PayCurrency='EUR' THEN Total END) EUR,
SUM(CASE WHEN PayCurrency='GBP' THEN Total END) GBP,
SUM(CASE WHEN PayCurrency='AUD' THEN Total END) AUD
FROM C
UNION
SELECT
'ToBePaid' T,
SUM(CASE WHEN PayCurrency='USD' THEN ToBePaid END) USD,
SUM(CASE WHEN PayCurrency='EUR' THEN ToBePaid END) EUR,
SUM(CASE WHEN PayCurrency='GBP' THEN ToBePaid END) GBP,
SUM(CASE WHEN PayCurrency='AUD' THEN ToBePaid END) AUD
FROM C
GO
我可以通过复制/粘贴为每个其他状态(未验证,已验证等等)完成并获得我想要的东西但是我的程序员希望拥有某种带有状态名称的功能并运行查询的模板化版本......
问题:我可以这样做吗?或者还有另一种更好的方法来打破我失踪的信息吗?
更新:我的目标是拥有这样的东西:
SELECT * FROM #mytempfunc('Total')
UNION SELECT * FROM #mytempfunc('ToBePaid')
UNION ...
答案 0 :(得分:2)
我不清楚你在问什么;您需要动态SQL来按字符串值选择字段。但是,如果您的指标列表是静态的(并且它应该来自视图),您可以使用UNPIVOT
得到您所需要的,或者至少更接近一点:
SELECT PayCurrency, Metric, Amount
FROM CampaignsPublisherReportSummary
UNPIVOT (Amount FOR Metric IN (Paid, ToBePaid, Total)) AS X