限制独立显示

时间:2017-03-29 02:29:09

标签: sql sql-server duplicates

我目前有这个SQL查询和这个输出。

id="form"

我得到这个输出: Output

如何删除与前两列不重复的所有行?

输出将是(在单词中获取所有客人的所有客人姓名和住宿日期,只有他们在同一家酒店住过多次):

SELECT b.HotelNo,g.guestName,b.dateFrom,b.dateToFrom Booking b, Guest g
FROM Booking b, Guest g
WHERE b.guestNo = g.guestNo
GROUP BY b.hotelNo,b.dateFrom,b.dateTo,g.guestName;

修改:
我得到了我想要的东西,但是当我将1234 John Doe 2017-02-01 00:00:00.000 2017-02-28 00:00:00.000 1234 John Doe 2017-03-16 00:00:00.000 2017-03-21 00:00:00.000 添加到我的select语句中时。我收到错误消息:b.dateFrom,b.dateTo

这是获取此错误的SQL查询:

Column 'Booking.dateFrom' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

如果我添加这两个列名(我需要),我会得到上面的错误。如何在不出错的情况下添加它们?

2 个答案:

答案 0 :(得分:0)

如果你不介意只挑选一个“dateFrom”(第一个或最后一个,具体取决于order子句),那么你可以为每一行分配一个行号,按前两列进行分区。 然后只挑选每组(RN = 1)的第一行,它们具有相同的前两列

WITH CTE AS
( SELECT ROW_NUMBER()   
          OVER ( PARTITION BY b.HotelNo,g.guestName 
            ORDER BY b.dateFrom) AS RN,
         b.HotelNo,g.guestName,b.dateFrom,b.dateTo
  FROM Booking b, Guest g
  WHERE b.guestNo = g.guestNo
  GROUP BY b.hotelNo,b.dateFrom,b.dateTo,g.guestName;
)
SELECT HotelNo,guestName,dateFrom,dateToFrom 
WHERE RN=1

您可以阅读更多HERE

答案 1 :(得分:0)

如果您只想要在酒店住宿多次的人,请使用JOIN或EXISTS条款来检查计数是否大于2。

使用EXISTS

SELECT DISTINCT b.hotelNo,g.guestName,b.dateFrom,b.dateTo 
FROM Booking AS b
JOIN Guest AS g 
    ON b.guestNo = g.guestNo
WHERE EXISTS 
(
    SELECT 1
    FROM Booking
    WHERE hotelNo = b.hotelNo
    AND guestNo = b.guestNo
    GROUP BY hotelNo, guestNo
    HAVING COUNT(*) > 1
);

使用JOIN(但原则相同):

SELECT DISTINCT b.hotelNo,g.guestName,b.dateFrom,b.dateTo 
FROM Booking AS b
JOIN Guest AS g 
    ON b.guestNo = g.guestNo
JOIN
(
    SELECT hotelNo, guestNo
    FROM Booking
    GROUP BY hotelNo, guestNo
    HAVING COUNT(*) > 1
) AS j
    ON j.hotelNo = b.hotelNo
    AND j.guestNo = b.guestNo;

注意:我不确定您的列上是否需要DISTINCTGROUP BY,除非您的表中确实存在重复项(如果您这样做,则为可能应该摆脱那些重复。)