我想获取以下场景的数据
输入:(现在说是:2015年3月1日)
LicenseNo LicenseEndDate LicenseType金额
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-Jully-2015 BC 140
预期的O / P
AB BC
0-3个月之间250 200
3-6个月之间120 140
这可能会增加
答案 0 :(得分:1)
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|
并将其用于您的加入
答案 1 :(得分:0)
在此解决方案中使用派生表只会使外部选择中的分组更容易,这样可以避免我们过多地重复自己。 SUM(case ... end)结构是一种旋转结果的方法,你可以看一下pivot运算符,但我认为这种情况有点过分。我还添加了一些其他情况,即使您提供的数据不使用它们,因为我认为它们很可能。如果你正在查看特定的组,你总是可以添加一个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