我有一个按 siteId 和状态拆分的项目表。
CREATE TABLE ItemDetail (
ItemNumber long,
SiteId int,
Status int,
Created datetime
)
然后我还有一个用户表
CREATE TABLE UserDetail (
UserId int,
Suspended int
)
状态有 7 个可能的值 (0-6) 代表不同的队列。我们称这个变量为 x。暂停,应该只有 0(活动)或 1(暂停)。(不要问我为什么它是一个 int,我没有构建它)。数据在可配置的时间范围内按站点显示。默认为 5 天前。我们称这个变量为 a。我想在一次调用中返回这样的数据集:
ActiveUserCount int
SuspendedUserCount int,
Queue0Count int,
Queue0TodayCount int,
Queue1Count int,
Queue1TodayCount int,
...
其中 QueueXCount 是过去几天按状态和站点 ID 划分的所有内容。QueueXTodayCount 是今天发生的所有状态为 x 的事件。到目前为止,我已经开始了这样的存储过程
CREATE PROCEDURE GetSiteStatistics
@SiteId int,
@Window int
AS
BEGIN
DECLARE @Today datetime
DECLARE @Tomorrow datetime
DECLARE @CutOff datetime
SET @Today = (CAST(YEAR(getdate()) as varchar) +
RIGHT('00' + CAST(MONTH(getdate()) as varchar), 2) +
RIGHT('00' + CAST(DAY(getdate()) as varchar), 2))
SET @Tomorrow = DATEADD(dd, 1, @Today)
SET @CutOff = DATEADD(dd, @Window + 1, @Today)
DECLARE
@SuspendedUserCount int,
@ActiveUserCount int,
@Queue0Count int,
@Queue0TodayCount int,
...
SELECT @SuspendedUserCount = count(UserId) FROM UserDetail WHERE Suspended = 1 AND SiteId = @SiteId
SELECT @ActiveUserCount = count(UserId) FROM UserDetail WHERE Suspended = 0 AND SiteId = @SiteId
SELECT @Queue0Count = count(ItemNumber) FROM ItemDetail WHERE Status = 0 AND SiteId = @SiteId AND Created >= @Today AND Created < @CutOff
SELECT @Queue0TodayCount = count(ItemNumber) FROM ItemDetail WHERE Status = 0 AND SiteId = @SiteId AND Created >= @Today AND Created < @Tomorrow
...
SELECT @SuspendedUserCount AS SuspendedUsers, @ActiveUserCount AS ActiveUsers, @Queue0Count AS Queue0, @Queue0TodayCount AS @Queue0Today...
END
好像这还不够复杂,我正在使用 Fluent Nhibernate。如果必须,我不反对使用存储过程,但我考虑过创建一个按天计数的视图,使用 nhibernate 和一个查询来按日期范围选择,然后在代码中适当地对数量求和。
我只是有一种感觉,我让这比我必须做的更复杂。肯定有更好的办法。