将结果与个人总数相结合

时间:2015-08-07 19:00:55

标签: sql sql-server sql-server-2012

我的数据库中有一个表,用于跟踪发送给各个用户和组的页面。用户是群组的一部分。只有个人用户才能回答页面。这是表格的DDL:

    --PageStatus 1 = Expired
    --PageStatus 2 = Answered
    --PageStatus 3 = Canceled

    CREATE TABLE [Pagings] (
    [Id] int NOT NULL IDENTITY(1,1) ,
    [UserProfileId] int NULL ,
    [GroupId] int NULL ,
    [Message] nvarchar(MAX) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    [PageStatus] int NOT NULL ,
    [DateCreated] datetime NULL ,
    [DateModified] datetime NULL ,
    [IsRecurring] bit NOT NULL DEFAULT ((0)) ,
    [AnsweredById] int NULL ,
    [AnsweredDateTime] datetime NULL ,
    CONSTRAINT [PK_ft.Pagings] PRIMARY KEY ([Id])
      )
    ON [PRIMARY]
    TEXTIMAGE_ON [PRIMARY]
    GO

PageStatus Expired(1)或Canceled(3)的任何时候,我们都没有AnsweredByIdAnsweredDateTime列的任何数据。如果已回答,则我们会在应答人员的UserProfileId列中设置来自应用程序的AnsweredById的值。如果对某个群组进行了分页,那么任何回答该网页的人都会被认为是该群组的一部分,并且他们的UserProfileId设置在AnsweredById列中。

以下是数据的示例结果和SqlFiddleenter image description here

我需要弄清楚如何获取用户的总页数,包括他们所属的组,他们回答的页数以及组总数。以下是基于上述集合的结果:

UserId GroupId  TotalPagesForUser  TotalAnsweredForUser TotalPagesForGroup TotalAnsweredForGroup
------ -------  -----------------  -------------------- ------------------ ----------------------
1       2         3                1                     1                 1
3       1         3                1                     2                 2
4       1         2                1                     2                 2

我已经尝试在UserProfileIdAnsweredById以及数据库中存在的Group表中将表加入到自身中,但我的结果已经过时了,我最终有很多重复的数据。

1 个答案:

答案 0 :(得分:1)

我将它分为两​​部分,首先汇总用户的聚合数字,然后在子查询中获取组号作为主查询的一部分,或者在结尾汇总结果的两个单独的查询。无论如何,我粗略的第一次尝试:

Select u.Id as UserId,  
g.Id as GroupId,
g.name as GroupName,
count(0) as TotalPagesForUser,
Sum(case when p.AnsweredById IS NOT NULL then 1 else 0 end) as TotalAnsweredForUser,
(SELECT COUNT(0) FROM Pagings WHERE GroupId = g.Id) as TotalPagesForGroup,
(SELECT COUNT(0) FROM Pagings WHERE GroupId = g.Id AND AnsweredById IS NOT NULL) as TotalAnsweredForGroup
from UserProfiles u
INNER JOIN Groups g on g.Id = u.GroupId
INNER JOIN Pagings p on p.UserProfileId = u.Id or p.AnsweredById = u.Id
GROUP BY u.Id, g.Id, g.name
ORDER BY u.Id

虽然我的价值观与您预测的价值略有不同......但我还没有机会详细查看源数据。