使选择查询条件相对

mHe*_*pMe 1 sql sql-server

我有两张桌子.

第一个表tblCPWgts,

       cp nvarchar(10)
       cDate date
       weight float
Run Code Online (Sandbox Code Playgroud)

第二表tblCP

       cp nvarchar(20)
       code nvarchar(5)
Run Code Online (Sandbox Code Playgroud)

我目前有一个如下查询

 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
Run Code Online (Sandbox Code Playgroud)

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

反正有没有调整我上面的查询,以便它不需要cp的硬编码?我在下面试过,但写完之后意识到它显然不起作用,但这就是我想要做的.

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
Run Code Online (Sandbox Code Playgroud)

art*_*rtm 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)
Run Code Online (Sandbox Code Playgroud)