sql - Combine results to count totals for individuals -
i have table in database keeps track of pages sent individual users , groups. users part of groups. individual users can answer pages. here ddl table:
--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
anytime pagestatus
expired
(1) or canceled
(3) not have data answeredbyid
or answereddatetime
columns. if answered set value of userprofileid
coming application in answeredbyid
column of person answered it. if group paged answered page assumed part of group , userprofileid
set inside answeredbyid
column.
here sample result , sqlfiddle accompany data.
i need figure out how total count of pages user including group belong to, how many pages answered, , group totals. here example of expect result based on set above:
userid groupid totalpagesforuser totalansweredforuser totalpagesforgroup totalansweredforgroup ------ ------- ----------------- -------------------- ------------------ ---------------------- 1 2 3 1 1 1 3 1 3 1 2 2 4 1 2 1 2 2
i've tried joining table on userprofileid
, answeredbyid
, group
table exists in database, results way off , end a lot of duplicated data.
i break 2 parts, first assemble aggregate numbers users, group numbers either in subquery part of main query or 2 separate queries results being assembled @ end. anyway, rough first attempt:
select u.id userid, g.id groupid, g.name groupname, count(0) totalpagesforuser, sum(case when p.answeredbyid not null 1 else 0 end) totalansweredforuser, (select count(0) pagings groupid = g.id) totalpagesforgroup, (select count(0) pagings groupid = g.id , answeredbyid not null) totalansweredforgroup 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 u.id, g.id, g.name order u.id
although i'm getting different values projecting...but haven't had chance on source data in detail yet.
Comments
Post a Comment