繁体   English   中英

SQL查询以根据日期范围获取数据

[英]SQL query to fetch data based on date range

我想在以下情况下获取数据

输入:(今天说:2015年3月1日)

LicenseNo LicenseEndDate LicenseType数量
1 2015年4月1日AB 100
2 2015年4月5日AB 150
3 BC 2015年4月7日
4 2015年7月10日AB 120
5 2015年7月10日BC 140

预期O / P

                  AB          BC

0-3个月之间250200
3-6个月之间120140
这可能会增加

SELECT 'Between 0-3 months', 
SUM(Case when l.LicenseType='AB' then l.Amount End), 
SUM(Case when l.LicenseType='BC' then l.Amount End)
FROM licence l
WHERE l.LicenceEndDate BETWEEN @inputDate AND DATEADD (month , 3 , @inputDate)

UNION

SELECT 'Between 3-6 months', 
SUM(Case when l.LicenseType='AB' then l.Amount End), 
SUM(Case when l.LicenseType='BC' then l.Amount End)
FROM licence l
WHERE l.LicenceEndDate BETWEEN DATEADD (month , 3 , @inputDate) AND DATEADD (month , 6 , @inputDate)

两个查询的两个间隔的并集。

或者您可以像这样根据输入日期创建一个临时表

|     ID | DESCRIPTION        | DATA_MIN | DATA_MAX  |
|      1 | Between 0-3 months | @input   | @input + 3|
|      2 | Between 3-6 months | @input +3| @input + 6|

并将其用于您的加入

在此解决方案中使用派生表只会使外部选择中的分组更加容易,这使我们免于重复太多。 SUM(case ... end)结构是透视结果的一种方法,您可以看一下透视运算符,但我认为这对于这种情况来说是过大的。 我还添加了一些其他情况,即使您提供的数据没有使用它们,因为我认为它们很有可能。 如果您要查看特定的组,则始终可以添加where子句,派生表也可以简化此子句。

我使用了GETDATE(),但如果更适合,则可以用日期变量代替。

declare @t as table 
(
    LicenseNo int, 
    LicenseEndDate datetime, 
    LicenseType varchar(2), 
    Amount numeric(10,2)
)

insert into @t
values
    (1,'1-Apr-2015','AB',100),
    (2,'5-Apr-2015','AB',150),
    (3,'7-Apr-2015','BC',200),
    (4,'10-July-2015','AB',120),
    (5,'10-july-2015','BC',140)

declare @comparison_date as datetime = getdate()

select 
    case ExpGrp
        when 0 then 'Expired'
        when 1 then 'Expires today'
        when 2 then 'Expires in 0-3 months'
        when 3 then 'Expires in 3-6 months'
        when 4 then 'Not due to expire'
        else 'Something went wrong'
    end as Descrip,
    sum(case when LicenseType = 'AB'
            then Amount
            else 0
        end) as AB,
    sum(case when LicenseType = 'BC'
            then Amount
            else 0
        end) as BC
from
    (select *,
        case 
            when LicenseEndDate < @comparison_date
                then 0
            when LicenseEndDate = @comparison_date
                then 1
            when LicenseEndDate > @comparison_date and LicenseEndDate <= dateadd(MONTH,3,@comparison_date)
                then 2
            when LicenseEndDate > dateadd(MONTH,3,@comparison_date) and LicenseEndDate <= dateadd(MONTH,6,@comparison_date)
                then 3
            else 4
        end as ExpGrp
    from @t) t
group by t.ExpGrp

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM