我如何创建一个(临时?)存储过程来帮助制作摘要视图?
我的视图表如下所示:
我开始创建一个视图来按每个状态进行总结货币:
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 ...
I have view table that looks like this:
And I started to create a view to summarize by status for each currency:
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
I could finish and get what I want by copy/pasting again for each of the other status (Unverified, Verified, ...etc) but the programmer in me wants to have some kind of function that takes the the status name and runs a templatized version of the query...
QUESTION: Can I do this? Or is there another better way to break the information down that I'm missing?
UPDATE: My goal is to have something like this:
SELECT * FROM #mytempfunc('Total')
UNION SELECT * FROM #mytempfunc('ToBePaid')
UNION ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不太清楚你在问什么;您需要动态 SQL 来按字符串值选择字段。但是,如果您的指标列表是静态的(而且应该是静态的,来自视图),则可以使用
UNPIVOT
获得所需的内容,或者至少更接近需要的内容:I'm not entirely clear on what you're asking; you'd need dynamic SQL to select a field by string value. However, if your list of metrics is static (and it should be, coming from a view), you may get what you need, or at least a little closer, with
UNPIVOT
: