这是一个改进的问题,基于我昨天的要求,并决定数据透视表太复杂,不能满足我的需要。我有以下代码,显示每个用户已完成的票数。
根据昨天类似帖子的建议(https://stackoverflow.com/users/2291321/ydaetskcor)建议将其简化为以下工作:
SELECT Names, COUNT(Names)
FROM Table1
GROUP BY Names
尽管我试图让我的代码在下面打球,但我仍然在努力弄清楚如何获得下面的代码来显示列表中每个用户的数量。
下面的代码显示了很长的用户列表但由于某种原因我无法显示它的唯一用户数(我知道这是一个相对简单的SQL!):
DECLARE @StartDate DateTime;
DECLARE @EndDate DateTime;
-- Date format: YYYY-MM-DD
SET @StartDate = '2013-11-06 00:00:00'
SET @EndDate = GETDATE() -- Today
SELECT (select Username from Membership where UserId = Ticket.CompletedBy) as TicketStatusChangedBy
FROM Ticket INNER JOIN
TicketStatus ON Ticket.TicketStatusID = TicketStatus.TicketStatusID INNER JOIN
Membership ON Ticket.CheckedInBy = Membership.UserId
WHERE TicketStatus.TicketStatusName = 'Completed' and Ticket.ClosedDate >= @StartDate --(GETDATE() - 1)
and Ticket.ClosedDate <= @EndDate --(GETDATE()-0)
ORDER BY Ticket.CompletedBy ASC, Ticket.ClosedDate ASC
显示以下内容
Paul
Matt
Matt
Bob
Matt
Paul
Matt
Matt
... (could be many different users)
理想情况下,我希望显示用户在列表中的次数,即
Paul | 2
Matt | 5
Bob | 1
答案 0 :(得分:1)
我稍微更改了你的查询。您加入了Membership
但未加入CompletedBy
列,但我认为没有任何理由这样做。我按Ticket.Id
计算,但我不确定那里是否存在此列,因此您可能需要更改它。
DECLARE @StartDate DateTime;
DECLARE @EndDate DateTime;
-- Date format: YYYY-MM-DD
SET @StartDate = '2013-11-06 00:00:00'
SET @EndDate = GETDATE() -- Today
SELECT Username, Count(Ticket.Id) as Count
FROM Ticket
INNER JOIN TicketStatus ON Ticket.TicketStatusID = TicketStatus.TicketStatusID
INNER JOIN Membership ON Ticket.CompletedBy = Membership.UserId
WHERE TicketStatus.TicketStatusName = 'Completed' and Ticket.ClosedDate >= @StartDate
and Ticket.ClosedDate <= @EndDate
GROUP BY Username
答案 1 :(得分:0)
您只需稍微重构一下您的查询。我还建议您再次使用表Membership
加入,而不是使用相关子查询:
DECLARE @StartDate DateTime;
DECLARE @EndDate DateTime;
-- Date format: YYYY-MM-DD
SET @StartDate = '2013-11-06 00:00:00'
SET @EndDate = GETDATE() -- Today
SELECT M2.Username AS TicketStatusChangedBy,
COUNT(*) N
FROM Ticket T
INNER JOIN TicketStatus TS
ON T.TicketStatusID = TS.TicketStatusID
INNER JOIN Membership M
ON T.CheckedInBy = M.UserId
LEFT JOIN Membership M2
ON T.CompletedBy = M2.UserId
WHERE TS.TicketStatusName = 'Completed'
AND T.ClosedDate >= @StartDate --(GETDATE() - 1)
and T.ClosedDate <= @EndDate --(GETDATE()-0)
GROUP BY M2.Username
ORDER BY M2.Username