0

这是一个改进的问题,基于我昨天提出的问题,并决定数据透视表对于我需要的东西来说太复杂了。我有以下代码,它显示了每个用户完成了多少票。

根据昨天类似帖子的建议(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
4

2 回答 2

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
于 2013-11-08T13:20:09.023 回答
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
于 2013-11-08T13:22:21.727 回答