我想获取以下场景的数据
输入:(假设今天是: 1-Mar-2015)
LicenseNo :许可证结束日期:许可证类型:金额
2011年4月1日-2015年4月1日-2015年4月1-日,该公司的资产负债表,AB公司的资产负债表,该公司的资产负债表,以及该公司的资产负债表,其价值为100%。
2015年4月5日-2015年4月5日-2015年4月上旬,AB,P5,- 150。
2015年4月7日-2015年4月7日-2015年4月3日,中国人民银行公布了中国人民银行的财政预算,该银行的财政预算为200亿美元。
2014年7月10日-2015年7月10日-7月10日-2015年7月10日-7月10日-7月10日-2015年7月10日-7月10日-7月10日
5-7月10日-2015年7月10日-7月10日-2015年7月10日-6月10日-7月10日-2015年7月10日-6月10日-7月10日-2015年7月10日
预期的O/P
AB BC在0-3个月之间,250个月内,每个月将会有250个月,而每个月将会有200个月。
在3-6个月内,120个月的时间间隔为120个月,而不是140个月。
这可能会增加
发布于 2015-03-18 03:10:59
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|并将其用于您的连接
发布于 2015-03-18 03:01:08
在这个解决方案中使用派生表只是使外部select中的分组更容易,它使我们不必重复太多。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.ExpGrphttps://stackoverflow.com/questions/29106895
复制相似问题