2

我有一个 sql 查询

select b.logtime,
       b.beam_current,
       b.beam_energy,
       case when a.st2_vs2_bag1_onoff=0 then c.st2_vs2_bag1_rb ELSE 0 END
         as st2_vs2_bag1_rb,
       CASE when a.st2_vs2_bag8_onoff=0 then c.st2_vs2_bag8_rb else '0' END
         as st2_vs2_bag8_rb,
       CASE when a.st2_vs2_bag9_onoff=0  then c.st2_vs2_bag9_rb else '0' END
         as st2_vs2_bag9_rb 
from   INDUS2_BDS.dbo.DCCT b
       INNER JOIN (
         INDUS2_VACUUM.dbo.main_vacuum_analog c
         inner join INDUS2_VACUUM.dbo.main_vacuum_status a
           on c.logtime=a.logtime
       )
       ON a.LOGTIME = b.LOGTIME
         and (b.beam_current like '%9.96' etc)
         and b.logtime between '2014-08-09 00:00:00' and '2014-08-09 23:59:59'
         and b.beam_current in('10.01', '20.02', etc)
         and ( b.beam_energy between '550' and '551' )
order by b.logtime 

现在在给定的日志时间中,单个 beam_current 值在不同的日志时间多次出现。我只想要一个不重复的 beam_current 值。为此,我想在上面的 Sql Query 中应用 row_number 并按 beam_current 分区。但我没有得到如何应用它。

4

1 回答 1

4

做了一些改动

删除了Join条件中不需要的括号。Join无条件也有错误ON,更正一下

然后只保留子句中的join条件On将过滤器移动到where子句。

试试这个。

;WITH cte
     AS (SELECT b.logtime,
                b.beam_current,
                b.beam_energy,
                CASE
                  WHEN a.st2_vs2_bag1_onoff = 0 THEN c.st2_vs2_bag1_rb
                  ELSE 0
                END                     AS st2_vs2_bag1_rb,
                CASE
                  WHEN a.st2_vs2_bag8_onoff = 0 THEN c.st2_vs2_bag8_rb
                  ELSE '0'
                END                     AS st2_vs2_bag8_rb,
                CASE
                  WHEN a.st2_vs2_bag9_onoff = 0 THEN c.st2_vs2_bag9_rb
                  ELSE '0'
                END                     AS st2_vs2_bag9_rb,
                Row_number() OVER(partition BY b.beam_current
                    ORDER BY b.logtime) RN
         FROM   INDUS2_VACUUM.dbo.main_vacuum_analog c
                INNER JOIN INDUS2_VACUUM.dbo.main_vacuum_status a
                        ON c.logtime = a.logtime
                INNER JOIN INDUS2_BDS.dbo.DCCT b
                        ON a.LOGTIME = b.LOGTIME
         WHERE  b.beam_current LIKE '%9.96'
                AND b.logtime BETWEEN '2014-08-09 00:00:00' AND '2014-08-09 23:59:59'
                AND b.beam_current IN ( '10.01', '20.02' )
                AND b.beam_energy BETWEEN '550' AND '551')
SELECT logtime,
       beam_current,
       beam_energy,
       st2_vs2_bag1_rb,
       st2_vs2_bag8_rb,
       st2_vs2_bag9_rb
FROM   cte
WHERE  rn = 1
ORDER  BY logtime 
于 2015-02-24T13:20:37.657 回答