SQL [CASE查询视图]

时间:2010-01-26 08:09:40

标签: sql-server view case

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 Something我需要来自BACS_Alarm_1表的输出字段WHERE... = 1,如果= 0则输出Null ...如果&gt;输出我的消息1(已经制作)

我怎么能意识到这种情况?

所以 如果

(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

我输出'&gt; 1'作为某种东西

if = 1我从dbo.BACS_Alarm_1输出一个字段 if = 0我输出0或null

1 个答案:

答案 0 :(得分:2)

保持原样,你可以写:

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视为可能的结果,我认为您也可以省略COUNT:

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

如果确实有更多可用的结果,并且原始中的COUNT可以产生超过1的结果,那么你可以这样写:

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