0

我想将某些列值“强制”到我的 sql 查询中。

例如,对于日期 2012-01-01,我总是希望列 Qs_to_first_default 从 1 变为 7。对于上一季度 2011-10-01,该列始终包含从 1 到 8 的值。

select 
*, convert(numeric(8,2),ANTAL)/convert(numeric(8,2),TOT_ANTAL) as Procentage
from
(
    select COUNT(*) as ANTAL,
    start_quarter, Qs_to_first_default
    from 
        (
        select Q1.RES_id, start_quarter, quarter_def, 
        DATEDIFF(quarter, start_quarter, quarter_def)+1 as Qs_to_first_default 
        from
            (
            select RES_id, cast(dateadd(quarter, datediff(quarter, 0, RES_datum),0) as date) as [start_quarter]
            from VFA_UPPF..Reservering 
            where RES_first=1 and RES_ao=500 and RES_produkt='Lån' 
            ) as Q1
        full join 
            (
            select
            cast(dateadd(quarter, datediff(quarter, 0, MIN(RES_datum)),0) as date)as [quarter_def], 
            CONVERT(date, MIN(RES_datum)) as RES_datum_def, 
            RES_id
            FROM VFA_UPPF..Reservering
            where RES_ao in ('500') and RES_produkt='Lån'
            and RES_kb_scoring NOT in ('1', '2', '3', '4', '5')
            GROUP BY RES_id
            ) as Q2 on Q1.RES_id=Q2.RES_id
        where start_quarter is NOT NULL
        ) as T1
    where Qs_to_first_default is NOT NULL
    group by start_quarter, Qs_to_first_default
) as S1
--joina med totalt antal startade varje kvartal
join 
    (
    select
    SUM(ANTAL1) as TOT_ANTAL, _quarter
    from
        (
        select COUNT(*) as ANTAL1, 
        cast(dateadd(quarter, datediff(quarter, 0, RES_datum),0) as date) as [_quarter]
        from VFA_UPPF..Reservering
        where RES_first=1 and RES_ao=500 and RES_produkt='Lån' 
        GROUP BY dateadd(quarter, datediff(quarter, 0, RES_datum),0), RES_datum
        ) as K1
    group by _quarter
    ) as T2 on S1.start_quarter=T2._quarter
where start_quarter<(select cast(dateadd(quarter, datediff(quarter, 0, MAX(RES_datum)),0) as date) from VFA_UPPF..Reservering)
and start_quarter>=(select cast(dateadd(quarter, datediff(quarter, 0, DATEADD(day, -1, DATEADD(month, -24, DATEADD(DAY,1,MAX(RES_datum))))),0) as date) from VFA_UPPF..Reservering)
order by start_quarter, Qs_to_first_default
4

1 回答 1

0

这是做你想做的吗?将外部更改select为:

SELECT ANTAL, start_quarter,
       (case when Qs_to_first_default < 1 then 1
             when start_quarter = '2012-01-01' and Qs_to_first_default > 7 then 7
             when start_quarter = '2011-01-01' and Qs_to_first_default > 8 then 8
             else Qs_to_first_default
        end) as Qs_to_first_default,
       convert(numeric(8,2),ANTAL)/convert(numeric(8,2),TOT_ANTAL) as Procentage
于 2013-08-26T12:42:08.520 回答