删除SQL Server中不需要的列Pivot

时间:2013-12-13 17:22:44

标签: sql sql-server database relational-database

我的表格是这样的:

CEID  BUID   WEIGHT TREND SCORE Quarter
---------------------------------------
CE001 BU001    4     5     20     1
CE001 BU001    4     0     22     2
CE001 BU001    4     0     23     3
CE001 BU001    4     0     24     4

我想要的结果是这样的

CEID  BUID   WEIGHT TREND Q1 Q2 Q3 Q4
---------------------------------------
CE001 BU001    4      NA  20 22 23 24

我写了以下Pivot查询:

select * 
from table
pivot (sum (score) for quarter in ([1],[2],[3],[4])) as ScorePerQuarter

但是由于趋势也在变化,我在Pivoted查询中也获得了多行...对于不同的趋势值..

如何实现上述结果?即:从查询中删除趋势列。

1 个答案:

答案 0 :(得分:1)

停止对主表使用SELECT *,并省略TREND列:

;WITH t AS
(
  select CEID, BUID, WEIGHT, SCORE, Quarter from dbo.table
)
SELECT * FROM t
pivot (sum (score) for quarter in ([1],[2],[3],[4])) as ScorePerQuarter;

如果您想要“我想要的结果”中显示的TREND = NA,只需对其进行硬编码:

;WITH t AS
(
  select CEID, BUID, WEIGHT, TREND = 'NA', SCORE, Quarter from dbo.table
)
SELECT * FROM t
pivot (sum (score) for quarter in ([1],[2],[3],[4])) as ScorePerQuarter;