sql server 2008转动多个列和动态列

时间:2017-01-06 08:18:10

标签: sql-server sql-server-2008 pivot pivot-table

我有两张桌子。我写了一个查询。日期是动态的。我可以选择任何日期。 `

select a.MP,a.CP,a.Frequency,a.Time,CONVERT(varchar(12),b.date,101) as 
EntryDate,b.actualtime from mpcp a, DailyData b 
where a.UserID=1 and a.MpCpId=b.MpCpId and 
CONVERT(varchar(12),b.EntryDate,101) between
CONVERT(varchar(12),GETDATE()-5,101) and 
CONVERT(varchar(12),GETDATE()+25,101)`

输出

enter image description here

但我希望输出像 enter image description here

3 个答案:

答案 0 :(得分:1)

假设我将结果存储在一个临时表和成像数据中,我为您的需求创建了一个数据

试试这个是否有用

create table #piv
(
mp varchar(10),
cp varchar(10),
freq varchar(10),
time int,
entryd date,
acuralize int
)
insert into #piv values
('don','asper','da',30,getdate(),0),
('dwm','donl','da',10,getdate(),3),
('qar','qpr','da',15,getdate(),5),
('qar','qpr','da',15,'01-16-17',5),
('qar','qpr','da',15,'01-15-17',5),
('qar','qpr','da',15,'01-16-17',5)

SELECT * FROM #piv
Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName(entryd) From #piv Order by 1 For XML Path('')),1,1,'')
Select  @SQL = '
Select *,' + @SQL + '
From #piv
 Pivot (max(time) For [entryd] in (' + @SQL + ') ) p'
Exec(@SQL);

答案 1 :(得分:0)

您可以创建动态枢轴。这个link就是一个很好的例子。

祝你好运!

答案 2 :(得分:0)

    DECLARE @cols VARCHAR(max),@sql VARCHAR(max)
    SELECT  @cols=ISNULL(@cols+',[','[')+ CONVERT(VARCHAR,a.EntryDate,101)+']'  
    FROM mpcp a, DailyData b 
    where a.UserID=1 and a.MpCpId=b.MpCpId and DATEDIFF(d,GETDATE(),b.EntryDate) BETWEEN -5 AND 25
    GROUP BY a.time

    SET @sql='
    SELECT * FROM (

        SELECT a.MP,a.CP,a.Frequency,a.Time,CONVERT(varchar(12),b.date,101) AS EntryDate,b.actualtime 
        FROM mpcp a, DailyData b 
        WHERE a.UserID=1 and a.MpCpId=b.MpCpId and  where a.UserID=1 and a.MpCpId=b.MpCpId and DATEDIFF(d,GETDATE(),b.EntryDate) BETWEEN -5 AND 25
  ) AS t 
  PIVOT (MAX(actualtime) FOR EntryDate IN ('+@cols+') )'
  EXEC(@sql)