2

我在找出 SQL Server 查询时遇到了一些麻烦。至少可以说,关系模型已经很老了(看起来)并且不是很理想。

我的查询如下所示:

SELECT 
    [RequestUsers].requestId, [Requests].name, [Requests].isBooked
FROM 
    [RequestUsers]
JOIN 
    [Requests] ON [RequestUsers].requestId = [Requests].id
WHERE 
    [RequestUsers].dateRequested >= '10-01-2013'
    AND [RequestUsers].dateRequested <= '10-16-2013'

此查询给出了重复记录的负载结果,即:

id      name        isBooked
-----------------------------
1393    Request1       0
1393    Request1       0
1393    Request1       0    
1394    Request2       0
1394    Request2       0
1399    Request3       0
1399    Request3       0
1399    Request3       0
1399    Request3       0
1399    Request3       0

(这里省略了很多记录)

我的问题是:有没有办法修改上述查询以对重复记录进行分组并创建一个requestCount包含重复次数的列?像这样:

id      name        isBooked     requestCount
---------------------------------------------
1393    Request1       0              3
1399    Request2       0              2
1393    Request3       0              5

? :-)

提前致谢!

4

3 回答 3

7
SELECT [RequestUsers].requestId, 
       [Requests].name, 
       [Requests].isBooked,
       Count(*) AS requestCount
FROM   [RequestUsers]
       JOIN [Requests]
           ON [RequestUsers].requestId = [Requests].id
WHERE  [RequestUsers].dateRequested >= '10-01-2013'
       AND [RequestUsers].dateRequested <= '10-16-2013'
GROUP BY [RequestUsers].requestId, 
       [Requests].name, 
       [Requests].isBooked
于 2013-10-16T19:53:07.960 回答
0
SELECT [RequestUsers].requestId, [Requests].name, [Requests].isBooked,
COUNT([RequestUsers].requestId) "requestCount"
FROM [RequestUsers]
JOIN [Requests]
ON [RequestUsers].requestId = [RequestUsers].id
WHERE [RequestUsers].dateRequested >= '10-01-2013'
AND [RequestUsers].dateRequested <= '10-16-2013'
GROUP BY [RequestUsers].requestId, [Requests].name, [Requests].isBooked
于 2013-10-16T19:55:06.830 回答
-1
    SELECT Distinct([RequestUsers].requestId), [Requests].name, [Requests].isBooked, Count([RequestUsers].requestId) as requestCount
    FROM [RequestUsers]
    JOIN [Requests]
    ON [RequestUsers].requestId = [RequestUsers].id
    WHERE [RequestUsers].dateRequested >= '10-01-2013'
    AND [RequestUsers].dateRequested <= '10-16-2013'
    GROUP BY [RequestUsers].requestId
于 2013-10-16T19:53:53.717 回答