TSQL-在简单的where条件中挣扎

时间:2019-01-09 15:46:48

标签: tsql

select 
    b.id, b.status, 
    b.max_log_data, 
    b.rn
from 
( 
    select 
    a.id, a.status, 
    a.max_log_date, 
    ROW_NUMBER() OVER (PARTITION BY a.id order by a.max_log_date) as rn
    from 
    (
        select id, status, max(log_date)'max_log_date' 
        from LOG_table where id=1234
        group by id, status
    ) as a 
) as b 
where ????

因此,在没有条件的结果中,我具有带日期和行号(rn)的不同状态,但是我需要特殊日期,其中行号等于具有特殊状态+ 1的行号

基本上我需要在什么条件下:b.rn =((具有特殊状态的b.nr)+1)

尝试过类似的操作,但这不起作用:b.rn =(b.status ='sold'然后b.rn + 1结束的情况)

1 个答案:

答案 0 :(得分:0)

在没有子查询的简单WHERE条件下,无法用另一行中的值过滤一行。您需要将它们连接在一起才能应用涉及这些列的表达式。

我发现使用CTE语法比子查询更易于阅读:

;WITH MaxLogDates AS 
(
    select 
        id, 
        status, 
        max(log_date) AS max_log_date
    from 
        LOG_table 
    where 
        id=1234
    group by 
        id, 
        status
),
RowNumbers AS
(
    select 
        a.id, 
        a.status, 
        a.max_log_date, 
        ROW_NUMBER() OVER (PARTITION BY a.id order by a.max_log_date) as rn
    from 
        MaxLogDates as a
),
FilteredStatusRowNumber AS
(
    SELECT
        R.id,
        R.status,
        R.max_log_date,
        R.rn AS SpecificRN
    FROM
        RowNumbers AS R
    WHERE
        R.Status = 'Some Specific Status'
)
select 
    r.id, 
    r.status, 
    r.max_log_data, 
    r.rn
from 
    RowNumbers as r
    INNER JOIN FilteredStatusRowNumber AS f on
        r.id = f.id AND
        R.rn = f.SpecificRN + 1

您还可以将ROW_NUMBER()直接应用于MAX()的总价值,并用1块石头杀死2只鸟:

select 
    id, 
    status, 
    max(log_date) AS max_log_date,
    ROW_NUMBER() OVER (PARTITION BY a.id order by max(log_date)) as rn
from 
    LOG_table 
where 
    id=1234
group by 
    id, 
    status