简体   繁体   English

删除SQL Server中不需要的列Pivot

[英]Remove unwanted columns Pivot in SQL Server

The table I have is like this: 我的桌子是这样的:

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

The result I want is like this 我想要的结果是这样的

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

I wrote the following Pivot query: 我编写了以下Pivot查询:

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

But since trend is also changing I am getting multiple rows in Pivoted query as well..for different values of trend.. 但是由于趋势也在发生变化,因此在不同的趋势值中,我也在Pivoted查询中获得了多行。

How can I achieve the result shown above? 如何获得上面显示的结果? ie: remove trend column from the query altogether. 即:从查询中完全删除趋势列。

Just stop using SELECT * against the main table, and leave out the TREND column: 只需停止对主表使用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;

If you want TREND = NA as shown in your "result i want", just hard-code it: 如果您希望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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM