添加列通過選擇來自sql Server中另一個表格的所有項目來選擇表格。 我拖表像這樣:添加列通過從sql Server中的另一個表中選擇所有項目來選擇表格
表1
ID || Title
1 || Ruler
2 || Book
3 || Pen
. || .
. || .
. || .
表2
itemID || Price || Date
1 || 200 || 2016-01-21
2 || 30 || 2017-03-01
3 || 27 || 2014-06-09
. || .
. || .
. || .
表結果
Date || Ruler || Book || pen || … more
2016-01-21 || 200 || || ||
2017-03-01 || || 30 || ||
2014-06-09 || || || 27 ||
.
.
.
它不工作
Declare @cols1 varchar(max)
Declare @query nvarchar(max)
Select @cols1 = stuff((select distinct ','+QuoteName([Title]) from table1 for xml path('')),1,1,'')
Set @Query = ' Select * from (
Select t2.[Date], t1.[Title], t2.Price from table2 t2 inner join table1 t1
on t2.ItemId = t1.Id) a pivot (max([Price]) for [Title] in (' [email protected] + ')) p '
exec sp_executeSql @query
其回報最高報價,但我想最後的價格就像這樣:
pivot (Select ([Price]) from table2 order by Date desc for [Title] in (' [email protected] + ')) p '
語法錯誤回報!?
你從哪兒弄來的語法'Table1.ID *'?嘗試從當前查詢中刪除'。*'。 –
可能重複的[SQL Server動態PIVOT查詢?](https://stackoverflow.com/questions/10404348/sql-server-dynamic-pivot-query) –