SELECT内部枢轴不正确

时间:2014-10-31 18:29:40

标签: sql sql-server-2012

SSMS突出显示行 FOR urlsByFilm.Media_Type_ID IN ...

BEGIN
    SELECT urlsByFilm.Film_ID, urlsByFilm.Media_Type_ID, urlsByFilm.Media_File_Name
    FROM [dbo].[Film_Media_Item] urlsByFilm
    PIVOT
    (
        MAX(urlsByFilm.Media_File_Name) 
        FOR urlsByFilm.Media_Type_ID IN (SELECT DISTINCT Media_Type_ID FROM [dbo].[Film_Media_Item])
    ) AS pivot

    WHERE API_ID in (@API_IDs)
END

我不能跑这个,你能帮忙吗?

1 个答案:

答案 0 :(得分:0)

您不能在IN子句中使用SQL表达式,您需要指定值。

    MAX(urlsByFilm.Media_File_Name) 
    FOR urlsByFilm.Media_Type_ID IN 
    (SELECT DISTINCT Media_Type_ID FROM [dbo].[Film_Media_Item])

您需要使用动态SQL来实现您的目标。

您的查询将使用动态SQL

DECLARE @cols NVARCHAR(2000)
SELECT  @cols = STUFF(( SELECT DISTINCT 
                                '],[' + Media_Type_ID
                        [dbo].[Film_Media_Item]
                        ORDER BY '],[' + Media_Type_ID
                        FOR XML PATH('')
                      ), 1, 2, '') + ']'

DECLARE @query NVARCHAR(4000)

SET @query = N'SELECT Media_File_Name, '+
    @cols +'
    FROM
    (SELECT urlsByFilm.Film_ID, urlsByFilm.Media_Type_ID, urlsByFilm.Media_File_Name
    FROM [dbo].[Film_Media_Item] urlsByFilm)p
    PIVOT
    (
        MAX(urlsByFilm.Media_File_Name) 
        FOR urlsByFilm.Media_Type_ID IN ( '+
        @cols +' )
    ) AS pvt
    WHERE API_ID in (@API_IDs)'

EXECUTE(@query)