SQL查询翻转值并使其成为新表中的字段

时间:2012-05-31 08:55:14

标签: sql-server-2005

我有下表

enter image description here

如何制作这样的输出

enter image description here

我使用此查询执行了上面的输出:

SELECT DISTINCT 
    C.RefVal, 
    C.CalibrationEventID, 
    C1.Result As "Trial One", 
    C2.Result AS "Trial Two", 
    C3.Result AS "Trial Three", 
    C4.Result AS "Trial Four", 
    C5.Result AS "Trial Five" 
FROM CalibrationTrials AS C 
INNER JOIN 
    (SELECT DISTINCT RefVal, Result FROM CalibrationTrials WHERE CalibrationEventID = 'CAL000001' AND RefVal = '1.0010'AND TrialNo = 1) As C1 
ON C1.RefVal = C.RefVal
INNER JOIN 
    (SELECT DISTINCT RefVal, Result FROM CalibrationTrials WHERE CalibrationEventID = 'CAL000001' AND RefVal = '1.0010'AND TrialNo = 2) As C2 
ON C2.RefVal = C.RefVal
INNER JOIN 
    (SELECT DISTINCT RefVal, Result FROM CalibrationTrials WHERE CalibrationEventID = 'CAL000001' AND RefVal = '1.0010'AND TrialNo = 3) As C3 
ON C3.RefVal = C.RefVal
INNER JOIN 
    (SELECT DISTINCT RefVal, Result FROM CalibrationTrials WHERE CalibrationEventID = 'CAL000001' AND RefVal = '1.0010'AND TrialNo = 4) As C4 
ON C4.RefVal = C.RefVal
INNER JOIN 
    (SELECT DISTINCT RefVal, Result FROM CalibrationTrials WHERE CalibrationEventID = 'CAL000001' AND RefVal = '1.0010'AND TrialNo = 5) As C5 
ON C5.RefVal = C.RefVal

WHERE C.CalibrationEventID = 'CAL000001' AND C.RefVal = '1.0010'
ORDER BY C.RefVal, C.CalibrationEventID

显然使用此查询时,输出仅固定为一个RefVal,即“1.0010”

为每个RefVal的CalibrationEventID输出image2格式的正确查询是什么?

1 个答案:

答案 0 :(得分:2)

以下是如何为查询使用PIVOT子句:

SELECT
  RefVal,
  CalibrationEventID,
  [1] AS [Trial One],
  [2] AS [Trial Two],
  [3] AS [Trial Three],
  [4] AS [Trial Four],
  [5] AS [Trial Five],
  [6] AS [Trial Six]
FROM CalibrationTrials
PIVOT (
  MAX(Result) FOR TrialNo IN ([1], [2], [3], [4], [5], [6])
) AS p

以上假设您的表格仅包含RefVal, CalibrationEventID, TrialNo, Result列。如果表中有更多列,则应首先分别选择这四个列,然后应用PIVOT。这里:

SELECT
  RefVal,
  CalibrationEventID,
  [1] AS [Trial One],
  [2] AS [Trial Two],
  [3] AS [Trial Three],
  [4] AS [Trial Four],
  [5] AS [Trial Five],
  [6] AS [Trial Six]
FROM (
  SELECT
    RefVal,
    CalibrationEventID,
    TrialNo,
    Result
  FROM CalibrationTrials
) AS c
PIVOT (
  MAX(Result) FOR TrialNo IN ([1], [2], [3], [4], [5], [6])
) AS p

这是必需的,因为PIVOT查询本质上是一个特殊情况GROUP BY查询。除Result之外的所有列都参与隐式分组。这就是为什么你应该摆脱那种在这种分组中不需要的东西。

这是另一种方法,没有PIVOT:

SELECT
  RefVal,
  CalibrationEventID,
  MAX(CASE TrialNo WHEN 1 THEN Result END) AS [Trial One],
  MAX(CASE TrialNo WHEN 2 THEN Result END) AS [Trial Two],
  MAX(CASE TrialNo WHEN 3 THEN Result END) AS [Trial Three],
  MAX(CASE TrialNo WHEN 4 THEN Result END) AS [Trial Four],
  MAX(CASE TrialNo WHEN 5 THEN Result END) AS [Trial Five],
  MAX(CASE TrialNo WHEN 6 THEN Result END) AS [Trial Six]
FROM CalibrationTrials
GROUP BY
  RefVal,
  CalibrationEventID