1
Editted as per @HLGM comments to make it a bit more robust.
根据@HLGM评论编辑,使其更加健壮。
Note that in it's current form, I assume that when
请注意,在它的当前形式中,我假设当
- all alarms equal 1, the range should be
NULL
所有报警均等于1,范围应为NULL
- only one alarm equals 0, the range is the value of this alarm.
只有一个警报等于0,范围是此警报的值。
If this does not suffice, OP might clarify what should be returned instead.
如果这还不够,OP可能会澄清应该返回的内容。
SQL Statement
;WITH Alarm (C1, C1Alarm, C2, C2Alarm, C3, C3Alarm, C4, C4Alarm) AS (
SELECT 12.44, 0, 99.43, 0, 4.43, 1, 43.33, 0
UNION ALL SELECT 12.44, 1, 99.43, 0, 4.43, 1, 43.33, 0
UNION ALL SELECT 1, 0, 2, 1, 3, 1, 4, 1
UNION ALL SELECT 1, 1, 2, 1, 3, 1, 4, 1
)
, AddRowNumbers AS (
SELECT rowNumber = ROW_NUMBER() OVER (ORDER BY C1)
, C1, C1Alarm
, C2, C2Alarm
, C3, C3Alarm
, C4, C4Alarm
FROM Alarm
)
, UnPivotColumns AS (
SELECT rowNumber, value = C1 FROM AddRowNumbers WHERE C1Alarm = 0
UNION ALL SELECT rowNumber, C2 FROM AddRowNumbers WHERE C2Alarm = 0
UNION ALL SELECT rowNumber, C3 FROM AddRowNumbers WHERE C3Alarm = 0
UNION ALL SELECT rowNumber, C4 FROM AddRowNumbers WHERE C4Alarm = 0
)
SELECT C1, C1Alarm
, C2, C2Alarm
, C3, C3Alarm
, C4, C4Alarm
, COALESCE(range1.range, range2.range)
FROM AddRowNumbers rowNumber
LEFT OUTER JOIN (SELECT rowNumber, range = MAX(value) - MIN(value) FROM UnPivotColumns GROUP BY rowNumber HAVING COUNT(*) > 1) range1 ON range1.rowNumber = rowNumber.rowNumber
LEFT OUTER JOIN (SELECT rowNumber, range = AVG(value) FROM UnPivotColumns GROUP BY rowNumber HAVING COUNT(*) = 1) range2 ON range2.rowNumber = rowNumber.rowNumber
Test script
;WITH Alarm (C1, C1Alarm, C2, C2Alarm, C3, C3Alarm, C4, C4Alarm) AS (
SELECT 12.44, 0, 99.43, 0, 4.43, 1, 43.33, 0
UNION ALL SELECT 12.44, 1, 99.43, 0, 4.43, 1, 43.33, 0
UNION ALL SELECT 1, 0, 2, 1, 3, 1, 4, 1
UNION ALL SELECT 1, 1, 2, 1, 3, 1, 4, 1
)
, AddRowNumbers AS (
SELECT rowNumber = ROW_NUMBER() OVER (ORDER BY C1)
, C1, C1Alarm
, C2, C2Alarm
, C3, C3Alarm
, C4, C4Alarm
FROM Alarm
)
, UnPivotColumns AS (
SELECT rowNumber, value = C1 FROM AddRowNumbers WHERE C1Alarm = 0
UNION ALL SELECT rowNumber, C2 FROM AddRowNumbers WHERE C2Alarm = 0
UNION ALL SELECT rowNumber, C3 FROM AddRowNumbers WHERE C3Alarm = 0
UNION ALL SELECT rowNumber, C4 FROM AddRowNumbers WHERE C4Alarm = 0
)
SELECT C1, C1Alarm
, C2, C2Alarm
, C3, C3Alarm
, C4, C4Alarm
, COALESCE(range1.range, range2.range)
FROM AddRowNumbers rowNumber
LEFT OUTER JOIN (SELECT rowNumber, range = MAX(value) - MIN(value) FROM UnPivotColumns GROUP BY rowNumber HAVING COUNT(*) > 1) range1 ON range1.rowNumber = rowNumber.rowNumber
LEFT OUTER JOIN (SELECT rowNumber, range = AVG(value) FROM UnPivotColumns GROUP BY rowNumber HAVING COUNT(*) = 1) range2 ON range2.rowNumber = rowNumber.rowNumber