添加列要通过选择sql Server中另一个表中的所有项来选择Table

时间:2017-06-22 15:33:56

标签: sql sql-server select

添加列要通过选择sql Server中另一个表中的所有项来选择Table。 我有这样的牵引表:

表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 ( ' +@cols1 + ' ) ) p '
exec sp_executeSql @query

它返回Max Price,但我想要最后价格像这样:

pivot (Select ([Price]) from table2 order by Date desc for [Title] in ( ' +@cols1 + ' ) ) p '

语法错误返回!?

1 个答案:

答案 0 :(得分:0)

您可以使用以下角色:

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 ([Ruler],[Book],[Pen]) ) p

对于动态标题列表,您可以查询如下:

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 ( ' +@cols1 + ' ) ) p '

exec sp_executeSql @query