我试图找到在给定时间段内承诺最少的所有LID。以下是我的表:
| requestDate | BID | LID | PercentageContributed | DateComitted
| 1/10/2016 | S7444319C | S2262450A | 0.25 | 18/10/2016
| 1/10/2016 | S7444319C | S4495282I | 0.25 | 7/10/2016
| 1/10/2016 | S7444319C | S4792394D | 0.25 | 28/10/2016
| 1/10/2016 | S7444319C | S7173102K | 0.25 | 9/10/2016
| 25/10/2016 | S9981233W | S2848191X | 1.00 | 13/11/2016
| 28/10/2016 | S7611209X | S2848191X | 0.33 | 13/11/2016
| 28/10/2016 | S7611209X | S4792394D | 0.33 | 4/11/2016
| 28/10/2016 | S7611209X | S7145303Q | 0.33 | 5/11/2016
我尝试过以下代码:
SELECT LID, COUNT(*) AS TotalNumCommitte
FROM Commits
WHERE DateCommitted BETWEEN '2015-11-03' AND '2017-01-09'
GROUP BY LID
但我只是设法得到以下内容:
| LID | TotalNumCommitte
| S2262450A | 1
| S2848191X | 2
| S4495282I | 1
| S4792394D | 2
| S7145303Q | 1
| S7173102K | 1
我想要实现的目标如下:
| LID | TotalNumCommitte
| S2262450A | 1
| S4495282I | 1
| S7145303Q | 1
| S7173102K | 1
我也尝试了以下内容:
SELECT MIN(TotalNumCommitted)
FROM (
SELECT LID, COUNT(*) AS TotalNumCommitted
FROM Commits
WHERE DateCommitted >= '2015-11-03'
AND DateCommitted <= '2017-01-09'
GROUP BY LID
) T1
但我只得到1(这是最低限度) 非常感谢你的帮助。
答案 0 :(得分:2)
假设现代SQL支持公用表表达式和排名函数,如下所示:
;WITH Counts as (
SELECT LID, COUNT(*) AS TotalNumCommitte
FROM Commits
WHERE DateCommitted BETWEEN '2015-11-03' AND '2017-01-09'
GROUP BY LID
), RankedCounts as (
SELECT *,RANK() OVER (ORDER BY TotalNumCommitte) as rk
FROM Counts
)
select *
from RankedCounts
where rk=1
答案 1 :(得分:2)
我认为最简单的方法是TOP WITH TIES
:
SELECT TOP (1) WITH TIES LID, COUNT(*) AS TotalNumCommitte
FROM Commits
WHERE DateCommitted BETWEEN '2015-11-03' AND '2017-01-09'
GROUP BY LID
ORDER BY TotalNumCommitte;
答案 2 :(得分:1)
在标准SQL中,您使用{/ 1}},如
FETCH FIRST ROW WITH TIES
在SQL Server中,您必须改为使用SELECT LID, COUNT(*) AS TotalNumCommitte
FROM Commits
WHERE DateCommitted BETWEEN '2015-11-03' AND '2017-01-09'
GROUP BY LID
ORDER BY COUNT(*)
FETCH FIRST ROW WITH TIES;
:
TOP (1) WITH TIES
答案 3 :(得分:1)
您可以将查询组与窗口函数组合使用:
select lid, totalnumcommitte
from (
select lid,
count(*) as totalnumcommitte,
rank() over (order by count(*)) as rnk
from commits
group by lid
) t
where rnk = 1
order by lid;
或使用公用表表达式:
with counts as (
select lid,
count(*) as totalnumcommitte,
rank() over (order by count(*)) as rnk
from commits
group by lid
)
select lid, totalnumcommitte
from counts
where rnk = 1
order by lid;
答案 4 :(得分:0)
SELECT LID, COUNT(*) AS TotalNumCommitte FROM Commits WHERE DateCommitted BETWEEN '2015-11-03' AND '2017-01-09'
GROUP BY LID
HAVING COUNT(*) =
(SELECT TOP 1 COUNT(*) AS TotalNumCommitted FROM Commits WHERE DateCommitted BETWEEN '2015-11-03' AND '2017-01-09'
GROUP BY LID ORDER BY TotalNumCommitted)
答案 5 :(得分:0)
您可以使用HAVING过滤聚合函数的结果(在本例中为计数),例如:
SELECT LID, COUNT(*) AS TotalNumCommitte
FROM Commits
WHERE DateCommitted BETWEEN '2015-11-03' AND '2017-01-09'
GROUP BY LID HAVING COUNT(*) = 1