2010-01-26 101 views
1
SELECT 
DT, FlowParam, Abs_P, T, Volume, Energy, FlowTime_T, 
    (SELECT ' > 1 ' AS Expr1 WHERE (
     (SELECT COUNT(*) AS Expr2 
      FROM dbo.BACS_Alarm_1 
      WHERE 
      (DT_T >= dbo.BACS_HourFlow_1.DT_T) AND 
      (DT_T <= dbo.BACS_HourFlow_1.DT_T + dbo.BACS_HourFlow_1.FlowTime_T) 
     ) > 1 
    )) AS Something 
FROM dbo.BACS_HourFlow_1 

我需要輸出領域AS SomethingBACS_Alarm_1表,如果WHERE... = 1和輸出Null如果= 0 ...和輸出我的消息,如果> 1(這已經制造)SQL [案件查詢視圖]

哪有我意識到這種情況?

所以 如果

(SELECT COUNT(*) AS Expr2 
    FROM dbo.BACS_Alarm_1 
    WHERE 
    (DT_T >= dbo.BACS_HourFlow_1.DT_T) AND 
    (DT_T <= dbo.BACS_HourFlow_1.DT_T + dbo.BACS_HourFlow_1.FlowTime_T) 
) > 1 

I輸出 '> 1' 的東西

如果= 1個I輸出從dbo.BACS_Alarm_1 場如果= 0 I輸出0或空的

+0

所以基本上,如果子查詢(輸出到'Something'列)的結果爲0,你希望它是'Null',如果是1,則輸出別的,如果它大於1,這是一個自定義消息? – Anthony 2010-01-26 08:24:20

+0

這是MySQL還是別的? – Anthony 2010-01-26 08:24:44

+0

什麼數據庫?您應該嘗試使用連接而不是相關的子查詢。 – 2010-01-26 08:24:59

回答

3

留下最原樣的,你可以寫:

SELECT 
DT, FlowParam, Abs_P, T, Volume, Energy, FlowTime_T, 
    CASE (
     SELECT COUNT(*) AS Expr2 
     FROM dbo.BACS_Alarm_1 
     WHERE (DT_T >= dbo.BACS_HourFlow_1.DT_T) 
     AND (DT_T <= dbo.BACS_HourFlow_1.DT_T + dbo.BACS_HourFlow_1.FlowTime_T) 
    ) WHEN 0 THEN NULL 
     WHEN 1 THEN ' > 1 ' 
     ELSE 'something else' 
    END AS Something 
FROM dbo.BACS_HourFlow_1 

儘管如此,我認爲它可以提高一點......我不認爲子查詢是必要的。既然你提到的值1和0作爲可能的結果,我想你可以省略算過:

SELECT DT 
,  FlowParam 
,  Abs_P 
,  T 
,  Volume 
,  Energy 
,  FlowTime_T 
,  CASE 
      WHEN dbo.BACS_Alarm_1.DT_T IS NULL THEN NULL 
      ELSE ' > 1' 
     END AS Something 
FROM  dbo.BACS_HourFlow_1 
LEFT JOIN dbo.BACS_Alarm_1 
ON   dbo.BACS_HourFlow_1.DT_T <= dbo.BACS_Alarm_1.DT_T 
AND   dbo.BACS_HourFlow_1.DT_T + dbo.BACS_HourFlow_1.FlowTime_T >=   dbo.BACS_Alarm_1DT_T 

如果真的有更多的成果更多鈔票,並在原來可以產生超過1 COUNT,你可以把它寫像這樣:

SELECT DT 
,  FlowParam 
,  Abs_P 
,  T 
,  Volume 
,  Energy 
,  FlowTime_T 
,  CASE COUNT(*) 
      WHEN 0 THEN NULL 
      WHEN 1 THEN ' > 1' 
      ELSE 'something else' 
     END AS Something 
FROM  dbo.BACS_HourFlow_1 
LEFT JOIN dbo.BACS_Alarm_1 
ON   dbo.BACS_HourFlow_1.DT_T <= dbo.BACS_Alarm_1.DT_T 
AND   dbo.BACS_HourFlow_1.DT_T + dbo.BACS_HourFlow_1.FlowTime_T >= dbo.BACS_Alarm_1DT_T 
GROUP BY BACS_HourFlow_1.DT 
,   BACS_HourFlow_1.FlowParam 
,   BACS_HourFlow_1.Abs_P 
,   BACS_HourFlow_1.T 
,   BACS_HourFlow_1.Volume 
,   BACS_HourFlow_1.Energy 
,   BACS_HourFlow_1.FlowTime_T 
+0

謝謝,但UNION呢? – Cynede 2010-01-26 08:57:05

+1

好吧,那是另一種可能性,是的。但我幾乎100%肯定這個解決方案會更冗長,性能更差。 – 2010-01-26 09:20:34

+0

很高興知道... 再次感謝您的理解:) – Cynede 2010-01-26 10:11:14