从具有重复项的列中获取所有值

时间:2013-02-06 19:48:16

标签: mysql sql group-by nested-queries

我在预订表上有一个SQL查询(属性:name,day,start,finish),它查找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

谢谢你的时间!

2 个答案:

答案 0 :(得分:1)

无法为名称

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

答案 1 :(得分: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