【发布时间】:2015-03-04 20:13:27
【问题描述】:
我有 3 个表 Customer、Applications、ApplicationHistory。我必须检索以下数据:
- 获取过去 3 个月内每位客户的平均申请数量
- 获取过去 3 个月至少有一项或多项申请的客户数量
我一直在尝试分组,但遇到以下问题:
ApplicationHistory 表中每个应用程序都有多个条目,现在确定如何消除它们 &
注意:已包含客户表,因为需要按客户类型过滤数据
您能否建议我如何才能做到这一点?
非常感谢,
我的解决方案(不起作用)
SELECT a.ApplicationId, a.CustomerId, count(*) count
from [application] a
inner join [applicationhistory] ah on a.ApplicationId = ah.ApplicationId
inner join Customer c on c.CustomerId = a.CustomerId
where ah.EventDate between @StartDateFilter and @EndDateFilter
--c.CustomerType in ( A, B)
group by a.ApplicationId, a.CustomerId
表结构:
Customer
Name CustomerId CustomerType
test1 1 A
test2 2 B
Applications
ApplicationId CustomerId
3 1
4 1
5 2
6 2
7 2
ApplicationHistory
ApplicationId EventDate EventType
3 2014-12-01 New
3 2014-12-01 Updated
3 2014-12-02 Withdrawn
4 2014-12-02 New
4 2014-12-03 Updated
5 2014-12-05 New
5 2014-12-06 Updated
5 2014-12-06 Updated
5 2014-12-07 Updated
6 2014-12-08 New
【问题讨论】:
-
您是否将“应用程序的平均数量”定义为在给定时间范围内 EventType 为“New”的 ApplicationHistories 或任何 EventType?
-
@Bernd:“平均应用程序数”是客户应用程序表中应用程序计数的平均值。此外,系统会在 ApplicationHistory 表中为客户所做的每个更改创建一行,即新应用程序、应用程序更新等。为了应用日期过滤器,我必须在查询中使用这个 ApplicationHistory 表,因为每个应用程序都有不止一行(针对不同的事件类型),我无法解决这个问题。
-
使用示例数据编辑您的问题。正如您所定义的,
Applications表没有“应用程序计数”。你可以得到应用程序的总数,但平均值并没有真正的意义。 -
@Gordon:对不起,我的意思是:“平均应用程序数量”是应用程序表中客户应用程序数量的平均值
-
@Maverick 。 . .那仍然没有意义。请使用您想要的结果编辑问题。您可以获得“总计”。 “平均”没有意义,除非您想要每月平均数。
标签: sql sql-server