使选择查询条件相对

时间:2016-11-25 08:51:00

标签: sql sql-server

我有两张桌子。

第一张表tblCPWgts,

       cp nvarchar(20)
       code nvarchar(5)

第二个表tblCP

 select * from
 (
    select cp, cDate, weight from tblCPWgts where cDate >= '2014-09-09'
 )source pivot(max(weight) for cp in ([AB], [CD], [EF]) as pvt order by cDate

我目前有一个如下的查询

select * from
 (
    select cp, cDate, weight from tblCPWgts where cDate >= '2014-09-09'
 )source pivot(max(weight) for cp in (select code from tblCP) as pvt order by cDate

这很好用。但是cp的数量将在未来发生变化。所以,而不是像上面那样硬编码([AB],[CD],[EF]),我想利用表格tblCP,其中列代码有AB,CD,EF。

无论如何都要调整我的查询,以便它不需要cp的硬编码?我在下面试过,但写完之后意识到它显然不起作用,但这就是我想要做的。

val oneRowDF = myDF.first // gives Array[Row]

2 个答案:

答案 0 :(得分:5)

将代码选择到变量中,然后使用它来构建动态查询。

declare @codes nvarchar(max) = ''

select @codes = @codes + '[' + code + '], '
from tblCP

set @codes = SUBSTRING(@codes, 1, LEN(@codes) - 1)

declare @q nvarchar(max)

set @q = 'select * from
 (
    select cp, cDate, weight from tblCPWgts where cDate >= ''2014-09-09''
 )source pivot(max(weight) for cp in (' + @codes + ') as pvt order by cDate'

exec(@q)

答案 1 :(得分:2)

尝试此动态查询。

            DECLARE @SQL AS VARCHAR(MAX)
            DECLARE @code AS VARCHAR (MAX)


            SELECT @code =
            COALESCE(@code + ', ','')+ QUOTENAME(code)
            FROM
            (
                SELECT distinct code from tblCP 

            ) AS B


            SET @SQL = '
            select * from
             (
                select cp, cDate, weight from tblCPWgts where 
                cDate >= ''2014-09-09''
             )source 

             pivot
             (max(weight) 

             for cp in (  '+@code+') 

             as pvt order by cDate'

            print (@SQL)

            EXEC  (@SQL)