我有一个表,其中保存每月的账单记录数据。假设Customer 1234是在1月/2月计费的,而Customer 2345是在1月/2月/3月计费的。我如何对这些进行分组以显示并发的月度计费周期。但还需要非并发计费月份,因此Customer 3456的计费时间为2月/1月/6月/8月
SELECT custName, month, billed, count(*) as Tally
FROM db_name
WHERE
GROUP BY需要的结果:
Customer 1234 was billed for 2 months Concurrent
Customer 2345 was billed for 3 months Concurrent
Customer 3456 was billed for 4 months Non-Concurrent有什么建议吗?
发布于 2009-10-15 21:05:04
如果月份存储为datetime字段,则可以使用DATEDIFF计算第一次账单和最后一次账单之间的月数。如果经过的月数等于账单总数,则账单是连续的。
select
'Customer ' + custname + ' was billed for ' +
cast(count(*) as varchar) + ' months ' +
case
when datediff(month,min(billdate),max(billdate))+1 = count(*)
then 'Concurrent'
else 'Non-Concurrent'
end
from @billing
where billed = 1
group by custname如果您将账单月份存储为整数,则可以直接使用减法,而不是使用DATEDIFF。将WHEN行替换为:
when max(billdate)-min(billdate)+1 = count(*) 但在这种情况下,我想知道你是如何区分年份的。
发布于 2009-10-15 20:50:29
如果月份都在一个序列中,并且我们将搜索限制到特定的年份,那么Min(月)+Count(账单次数)-1应该=Max(月)。
declare @billing table(Custname varchar(10), month int, billed bit)
insert into @billing values (1234, 1, 1)
insert into @billing values (1234, 2, 1)
insert into @billing values (2345, 3, 1)
insert into @billing values (2345, 4, 1)
insert into @billing values (2345, 5, 1)
insert into @billing values (3456, 1, 1)
insert into @billing values (3456, 3, 1)
insert into @billing values (3456, 9, 1)
insert into @billing values (3456, 10, 1)
Select CustName, Count(1) as MonthsBilled,
Case
when Min(Month) + Count(1) - 1 = Max(Month)
then 1
else 0
end Concurrent
From @billing
where Billed = 1
Group by CustName
Cust Months Concurrent
1234 2 1
2345 3 1
3456 4 0发布于 2009-10-16 01:00:29
这里的建议基于一个假设,即您永远不会在同一个月向客户支付两次或更多账单。如果这不是一个安全的假设,那么您需要一种不同的方法。如果是这样,请让我们知道。
https://stackoverflow.com/questions/1574838
复制相似问题