动态透视(在 SQL Server 2005 中)
我正在为 Microsoft SQL 2005 编写一个存储过程,我想创建一个动态 SQL Pivot:
SELECT Book.ISBN,
Book.Name
StockMutation.StockLocation
FROM Book INNER JOIN StockMutation AS sm ON Book.bookid = sm.bookid
PIVOT
(
COUNT(sm.NumberOfBooks)
FOR sm.StockLocation IN (...)
)
最好我想将 (...) 替换为:
SELECT StockLocation.StockLocation FROM StockLocation
而不是硬编码过程中的所有位置 ([Location1],[Location2],等),但 SQL 不接受这一点。
我该如何解决这个问题?
I'm writing a stored procedure for Microsoft SQL 2005 and I want to create a dynamic SQL Pivot:
SELECT Book.ISBN,
Book.Name
StockMutation.StockLocation
FROM Book INNER JOIN StockMutation AS sm ON Book.bookid = sm.bookid
PIVOT
(
COUNT(sm.NumberOfBooks)
FOR sm.StockLocation IN (...)
)
Preferable I want to replace (...) with:
SELECT StockLocation.StockLocation FROM StockLocation
and not hardcode all locations in the procedure ([Location1],[Location2],etc.), but SQL doesn't accept this.
How do I solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能用纯 SQL 来做到这一点,你必须使用动态 SQL 并构建你想要执行的实际 SQL。
你可以这样做:
You can't do it in pure SQL, you have to use dynamic SQL and build the actual SQL you want to execute.
You can do this like so: