2017-06-22 78 views
0

添加列通过选择来自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 ' 

语法错误回报!?

+0

你从哪儿弄来的语法'Table1.ID *'?尝试从当前查询中删除'。*'。 –

+1

可能重复的[SQL Server动态PIVOT查询?](https://stackoverflow.com/questions/10404348/sql-server-dynamic-pivot-query) –

回答

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

exec sp_executeSql @query 
+0

**谢谢**,为您的答案 –

+0

'pivot(max ([+ @ cols1 +'))中的[标题]的价格([价格]))p'' 其返回的最大价格,但我想要最后的价格像这样: 'pivot(** Select([Price])from table2 ('+ @ cols1 +'))中的[标题],按日期排序desc ** p'' 语法错误返回!? –

+0

您能否提供更多的输入样本数据? –

相关问题