0

我在预订表(属性:名称、日期、开始、完成)上有一个 SQL 查询,它找到了 days 属性的重复值:

SELECT day, COUNT(day) as NumberOfTimes 
FROM reservation group by day HAVING (COUNT(day)>1) 
ORDER BY NumberOfTimes

但它只返回日期,并且当天的次数列在预订表中。我正在尝试返回以列出当天列出的每个名称,但我在查询分组时遇到了问题。我应该如何处理这是我希望返回看起来像:

BOB   MONDAY  3
JOHN  MONDAY  3
STEVE MONDAY  3
ALICE WEDNESDAY 2
MARTIN WEDNESDAY 2

谢谢你的时间!

4

2 回答 2

1

你不能为名称添加一列吗

SELECT
  name,
  day,
  COUNT(day) as NumberOfTimes
FROM reservation
group by name , day
HAVING (COUNT(day) > 1)
ORDER BY NumberOfTimes
于 2013-02-06T19:51:35.437 回答
1

您可以使用子查询,这将允许您添加更多不包括在的列GROUP BY

select r1.name,
    r2.day,
    r2.NumberOfTimes
from reservation r1
inner join
(
    SELECT day, COUNT(day) as NumberOfTimes 
    FROM reservation 
    group by day 
    HAVING (COUNT(day)>1) 
) r2
    on r1.day = r2.day
order by NumberOfTimes 

如果您只想将名称作为附加列,则可以使用:

SELECT name, day, COUNT(day) as NumberOfTimes 
FROM reservation 
group by day, name
HAVING (COUNT(day)>1) 
order by NumberOfTimes 
于 2013-02-06T19:52:14.840 回答