首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQL如何从多个查询中进行一个查询

SQL如何从多个查询中进行一个查询
EN

Stack Overflow用户
提问于 2009-10-16 04:30:01
回答 5查看 182关注 0票数 0

我有一个表,其中保存每月的账单记录数据。假设Customer 1234是在1月/2月计费的,而Customer 2345是在1月/2月/3月计费的。我如何对这些进行分组以显示并发的月度计费周期。但还需要非并发计费月份,因此Customer 3456的计费时间为2月/1月/6月/8月

代码语言:javascript
复制
SELECT custName, month, billed, count(*) as Tally
FROM db_name
WHERE
GROUP BY

需要的结果:

代码语言:javascript
复制
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

有什么建议吗?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2009-10-15 21:05:04

如果月份存储为datetime字段,则可以使用DATEDIFF计算第一次账单和最后一次账单之间的月数。如果经过的月数等于账单总数,则账单是连续的。

代码语言:javascript
复制
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行替换为:

代码语言:javascript
复制
when max(billdate)-min(billdate)+1 = count(*) 

但在这种情况下,我想知道你是如何区分年份的。

票数 1
EN

Stack Overflow用户

发布于 2009-10-15 20:50:29

如果月份都在一个序列中,并且我们将搜索限制到特定的年份,那么Min(月)+Count(账单次数)-1应该=Max(月)。

代码语言:javascript
复制
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
票数 1
EN

Stack Overflow用户

发布于 2009-10-16 01:00:29

这里的建议基于一个假设,即您永远不会在同一个月向客户支付两次或更多账单。如果这不是一个安全的假设,那么您需要一种不同的方法。如果是这样,请让我们知道。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1574838

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档