如何将Oracle多参数子查询转换为MS SQL子查询(ies)

时间:2014-03-07 18:14:57

标签: sql-server oracle

我们正在将一些旧的Oracle内容转换为MS SQL Server,而Oracle有多参数子查询,我正试图弄清楚如何在MS SQL Server中执行此操作。我对Oracle语法不是很熟悉,而且我很难弄清楚如何转换它。

原始where子句的相关部分是:

and (rate.tax_code, rate.effect_date) in 
        (select tax_code, max(effect_date)
         from   v_txtaxrate
         where  effect_date <= '10-JAN-14'
         group by tax_code)   

我尝试将它作为两个子查询:

and rate.tax_code in 
    (select tax_code
         from   v_txtaxrate
         where  effect_date <= '10-JAN-14'
         group by tax_code)
and rate.effect_date in 
    (select max(effect_date)
         from   v_txtaxrate
         where  effect_date <= '10-JAN-14'
         group by tax_code);

但结果显示这些不相同。

3 个答案:

答案 0 :(得分:3)

oracle代码要求[rate]。[tax_code]行的[effect_date]与视图中最新的一行相同。

<强>正确吗

-- ORACLE SNIPPET
and (rate.tax_code, rate.effect_date) in 
       (select tax_code, max(effect_date)
         from v_txtaxrate
         where  effect_date <= '10-JAN-14'
         group by tax_code) 

因此,派生表的内部联接只是解决了这个问题。派生表会获取每个税码的最新日期。

-- TSQL SNIPPET
select 
  *
from 
  rate inner join 
  (
    select tax_code, max(effect_date) as max_effect_date
    from  v_txtaxrate
    where  effect_date <= '20140110'
    group by tax_code
  )  d_tax
on
  rate.tax_code = d_tax.tax_code and
  rate.effect_date = d_tax.max_effect_date

由于我没有要测试的模式,因此我将[rate]表加入到代码和生效日期的派生[d_tax]税表中。退出在此联接中不匹配的任何记录。

请参阅我关于派生表的博客文章。

http://craftydba.com/?p=1144

此外,使用通用的日期文字。 'YYYYMMDD'就是这样一种格式。请参阅MSDN上的矩阵,显示哪些格式使用最多。

http://technet.microsoft.com/en-us/library/ms180878(v=sql.105).aspx

答案 1 :(得分:0)

我会使用“EXISTS”代替“IN”:

and exists (
  select 1 
  from (select tax_code, max(effect_date) effect_date
         from   v_txtaxrate
         where  effect_date <= '10-JAN-14'
         group by tax_code) a
  where rate.tax_code = a.tax_code
    and rate.effect_date = a.effect_date
)

答案 2 :(得分:0)

试试这个

and exists
(
    select tax_code, effect_date
    from
    (
        select tax_code, max(effect_date) as effect_date
        from   v_txtaxrate
        where  effect_date <= '10-JAN-14'
        group by tax_code
    ) t
    where tax_code = rate.tax_code
    and effect_date =  rate.effect_date
)