如何使用Pivot在SQL中重新组织查询结果

时间:2013-10-29 13:41:16

标签: sql pivot

我有一个返回如下所示数据的查询:

Project Name   Analyte   Result

A                 BOD       4mg/l

A              COD       10mg/l

B              BOD       4mg/l

B              COD       10mg/l

但我需要它看起来像这样:

Project Name   Analyte   Result   Analyte  Result

A              BOD       4mg/l        COD      10mg/l

B              BOD       4mg/l        COD      10mg/l

我无法弄清楚如何用sql做到这一点。枢轴功能会这样做吗?怎么样?

2 个答案:

答案 0 :(得分:0)

假设您总是会有一个BOD和一个COD

SELECT
  [a].[Project Name],
  [a].[Analyte] AS [Analyte1],
  [a].[Result] AS [Result1],
  [b].[Analyte] AS [Analyte2],
  [b].[Result] AS [Result2]
FROM
  [Results] [a]
  JOIN [Results] [b]
    ON [a].[Project Name] = [b].[Project Name]
WHERE
  [a].[Analyte] = 'BOD'
  AND [b].[Analyte] = 'COD';

SqlFiddle

答案 1 :(得分:0)

您没有指定您正在使用的RDBMS,但您可以轻松地使用带有CASE表达式的聚合函数来获得结果:

select
  projectName,
  max(case when Analyte = 'BOD' then Analyte end) Analyte_BOD,
  max(case when Analyte = 'BOD' then Result end) Result_BOD,
  max(case when Analyte = 'COD' then Analyte end) Analyte_COD,
  max(case when Analyte = 'COD' then Result end) Result_COD
from yourtable
group by projectname;

请参阅SQL Fiddle with Demo