2016-11-25 85 views
1

我有兩個表。使選擇查詢條件相對

一臺tblCPWgts,

 cp nvarchar(10) 
     cDate date 
     weight float 

二表tblCP

 cp nvarchar(20) 
     code nvarchar(5) 

目前我有類似下面

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 

這工作正常查詢。然而,cp的數量將在未來發生變化。因此,而不是像上面([AB],[CD],[EF])那樣對它們進行硬編碼。我想使用列碼爲AB,CD,EF的表tblCP。

有無論如何調整我的查詢上面,以便它不需要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 
+0

你需要建立一個動態查詢並使用'exec()' – artm

+0

我明白了,我該怎麼做? – mHelpMe

回答

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) 
+0

我在關鍵字'as'附近得到了一個不正確的語法 – mHelpMe

+0

不理我,很愚蠢! – mHelpMe

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 ( '[email protected]+') 

      as pvt order by cDate' 

      print (@SQL) 

      EXEC (@SQL) 
+0

@mHelpMe是否適合你。 ? –