1

http://sqlfiddle.com/#!3/e4891/1

对于上面生成的查询(数据透视),我想再运行一个选择条件。

例如

select (C1 & C2) from 'the above pivoted query results'</p>

有可能吗?CTE会在这里帮助吗?SQL Server 2008 及更高版本。

4

2 回答 2

1

试试这个:

WITH Data AS 
(
  select *
 from 
 (
    select MemId, Condition_id, condition_result
    from t
 ) x
 pivot
 (
    sum(condition_result)
    for condition_id in ([C1], [C2], [C3], [C4])
 ) p
)
SELECT C1, C2
  FROM Data

SQLFiddle:http ://sqlfiddle.com/#!3/e4891/3

于 2012-07-25T20:30:07.707 回答
0

要么将您的选择更改为仅选择您想要的字段:

select [C1], [C2]
  from 
  (
      select MemId, Condition_id, condition_result
      from t
  ) x
  pivot
  (
      sum(condition_result)
      for condition_id in ([C1], [C2], [C3], [C4])
  ) p

或者

;with cte
as
(
  select *
  from 
  (
      select MemId, Condition_id, condition_result
      from t
  ) x
  pivot
  (
      sum(condition_result)
      for condition_id in ([C1], [C2], [C3], [C4])
  ) p
)
select [C1], [C2]
from cte
于 2012-07-25T20:31:13.430 回答