SQL PIVOT 从列表中选择(IN SELECT)

发布于 2024-11-08 14:57:03 字数 487 浏览 0 评论 0原文

是否可以执行数据透视并从表中选择列表,而不是使用单个值?

像这样(不正确的语法错误):

SELECT *
FROM (
    SELECT RepID, MilestoneID, ResultID FROM RM
) AS src
PIVOT (
    MAX(ResultID) FOR MilestoneID IN  (SELECT id FROM m) 
) AS pvt

这个可以编译,但对我不起作用:

SELECT *
FROM (
    SELECT RepID, MilestoneID, ResultID FROM RM
) AS src
PIVOT (
    MAX(ResultID) FOR MilestoneID IN  ([1], [2], [3], [4]) 
) AS pvt

PS:我不想使用动态 SQL,有没有一种方法可以在不使用动态 SQL 的情况下做到这一点?

Is it possible to do a PIVOT and select list from a table, instead of using single values?

Like this (incorrect syntax error):

SELECT *
FROM (
    SELECT RepID, MilestoneID, ResultID FROM RM
) AS src
PIVOT (
    MAX(ResultID) FOR MilestoneID IN  (SELECT id FROM m) 
) AS pvt

This one compiles, but doesn't work for me:

SELECT *
FROM (
    SELECT RepID, MilestoneID, ResultID FROM RM
) AS src
PIVOT (
    MAX(ResultID) FOR MilestoneID IN  ([1], [2], [3], [4]) 
) AS pvt

PS: I do NOT want to use dynamic SQL, is there a way to do this without using dynamic SQL?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烟织青萝梦 2024-11-15 14:57:03

如果动态SQL出来了,恐怕答案是否定的,做不到。解析器需要预先知道这些值才能执行列转换。

If dynamic SQL is out then I'm afraid the answer is no, it can't be done. The parser needs to know the values up front to perform the pivot to columns.

神魇的王 2024-11-15 14:57:03

这是可以做到的。

DECLARE @idList varchar(500)
SELECT @idList = COALESCE(@idList + ',', '') + id
FROM m


DECLARE @sqlToRun varchar(1000)
SET @sqlToRun = '
SELECT * 
FROM ( 
    SELECT RepID, MilestoneID, ResultID FROM RM 
) AS src 
PIVOT ( 
    MAX(ResultID) FOR MilestoneID IN  ('+ @idList +')  
) AS pvt'   

EXEC (@sqlToRun)

It Can be done.

DECLARE @idList varchar(500)
SELECT @idList = COALESCE(@idList + ',', '') + id
FROM m


DECLARE @sqlToRun varchar(1000)
SET @sqlToRun = '
SELECT * 
FROM ( 
    SELECT RepID, MilestoneID, ResultID FROM RM 
) AS src 
PIVOT ( 
    MAX(ResultID) FOR MilestoneID IN  ('+ @idList +')  
) AS pvt'   

EXEC (@sqlToRun)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文