强制sql语句中的行

时间:2013-08-26 12:05:09

标签: sql scripting

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

E.g。对于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

1 个答案:

答案 0 :(得分: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