3

私はこの表を下に持っています

ここに画像の説明を入力

このような出力を行うにはどうすればよいですか

ここに画像の説明を入力

このクエリを使用して上記の出力を行いました。

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

どうやらこのクエリでは、出力は '1.0010' である 1 つの RefVal にのみ固定されます。

CalibrationEventID の各 RefVal に対して image2 形式を出力するための正しいクエリは何ですか?

4

1 に答える 1

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。テーブルにさらに列がある場合は、最初にこれら4つを個別に選択してから、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クエリが本質的に特殊なケースのGROUPBYクエリであるためです。を除くすべての列は、暗黙的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
于 2012-05-31T09:31:54.743 に答える