SQL Server计算动态列

时间:2014-08-26 09:07:02

标签: sql sql-server

有一个给定的表具有以下结构:

DateAndTime             | Count Wine | Count Beer

2014-08-11 16:45:22.480 | 100        | 50

2014-08-12 16:45:22.480 | 50         | 50

2014-08-18 16:45:22.480 | 200        | 100

2014-08-19 16:45:22.480 | 300        | 200

我需要的是一个带有以下输出的选择语句:

---  | Week No 33 | Week No 34

Beer | 50         | 150

Wine | 75         | 250 

所以列(周号)动态依赖于数据。 并且calaculated值应该是日历周内行的平均值。

我不知道如何解决这个问题....

2 个答案:

答案 0 :(得分:0)

不确定它是否是一种优雅的方式......但这样可行。

create table sample 
(
dtdate smalldatetime,
cWine int,
cBeer int
)

insert into sample 
values('2014-08-11 16:45:22.480', 100 , 50),('2014-08-12 16:45:22.480', 50, 50),
('2014-08-18 16:45:22.480', 200 , 100),('2014-08-19 16:45:22.480', 300 , 200)



   DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX)
   select @cols = STUFF((SELECT distinct ',' + QUOTENAME(DATEPART(WEEK,dtDate)) from sample  FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')


    SELECT @query = 'SELECT Countname, '+@cols+'
FROM
(

  SELECT countName,y,Avg(CountValue)avge from 

(
SELECT countName,countValue,dtdate,DATEPART(WEEK,dtdate)as y from  sample
unpivot(
countValue for Countname in (cwine,cBeer)
)unpiv )x group by y,countName


) x
pivot
(
  sum(avge)
  for y in ('+@cols+')
) p'


execute(@query)

答案 1 :(得分:0)

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(DATEPART(WEEK,dtdate)) 
                    from master.sample 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')



 SELECT @query = 'SELECT Countname, '+@cols+'
FROM
(

  SELECT countName,y,Avg(CountValue)avge from 

(
SELECT countName,countValue,dtdate,DATEPART(WEEK,dtdate)as y from  sample
unpivot(
countValue for Countname in (cwine,cBeer)
)unpiv )x group by y,countName


) x
pivot
(
  sum(avge)
  for y in ('+@cols+')
) p'

SELECT @query 
execute(@query)