我有以下代码,显示用户已完成票证的内容,并列出每个用户以及他们关闭票证的日期。即。
Paul
Matt
Matt
Bob
Matt
Paul
Matt
Matt
目前,我自己手动计算每个用户,以查看当天的总计。
编辑:将输出更改为列而不是行:
我一直试图让SQL Server为我做这件事,即最终结果如下:
Paul | 2
Matt | 5
Bob | 1
我目前正在使用的代码是,如果有人可以帮助我改变这一点,我会很高兴,所以我可以输出类似于上面的内容吗?
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
感谢您的帮助和时间。
答案 0 :(得分:1)
不确定你是否特别希望它采用这种格式,但如果你在行中使用它,它就像查询一样简单:
SELECT Names, COUNT(Names)
FROM Table1
GROUP BY Names
答案 1 :(得分:0)
CREATE TABLE SomeTable
(Name NVARCHAR(20))
GO
INSERT INTO SomeTable
VALUES ('Mark'), ('Mark'),('Mark'),('SAM'),('SAM'),('Josh')
GO
;WITH CTE
AS
(
SELECT NAME, COUNT(*) AS Total FROM SomeTable
GROUP BY Name
)
SELECT *
FROM CTE
PIVOT (
MAX(Total)
FOR NAME
IN ([Mark], [SAM], [Josh])
)l
结果集
Mark SAM Josh
3 2 1
显然如果表中有很多值你需要使用Dynamic Sql,首先构建所有不同值/名称的逗号分隔列表,然后在上面的'IN'cluase中传递名称列表查询它动态Sql。
使用动态SQL
DECLARE @NameList NVARCHAR(MAX) = ''
DECLARE @Sql NVARCHAR(MAX)
SELECT @NameList = @NameList + ',[' + Name + ']'
FROM (SELECT DISTINCT NAME FROM SomeTable)t
SET @NameList = STUFF(@NameList, 1, 1, '')
PRINT @NameList --<---- for checking purpose to see if list is as expected
SET @Sql = ';WITH CTE
AS
(
SELECT NAME, COUNT(*) AS Total FROM SomeTable
GROUP BY Name
)
SELECT *
FROM CTE
PIVOT (
MAX(Total)
FOR NAME
IN ('+ @NameList + ')
)l'
EXECUTE sp_executesql @Sql
结果集
Mark SAM Josh
3 2 1
答案 2 :(得分:0)
Declare @t table(names varchar(100))
DECLARE @StartDate DateTime;
DECLARE @EndDate DateTime;
-- Date format: YYYY-MM-DD
SET @StartDate = '2013-11-06 00:00:00'
SET @EndDate = GETDATE() -- Today
insert into @t(names)
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
Select
sum(case when names='Paul' then 1 else 0 end) as Paul,
sum(case when names='Matt' then 1 else 0 end) as Matt,
.
.
.
from @t