Pregunta

I am working on a booking system. A bug allowed some units to be a duplicate booking.

Using Microsoft SQL Server 2012 Express

IE, unit x is booked for two clients with the same checkIn date.

The bug has been fixed, but I want to check if any units were indeed duplicately booked.

I am battling to make a SQL query work to return these "duplicate" units. I can handle this in code with a few routines, but I was hoping to get an SQL query to show me these units.

I attempted a join (on the same table), which just returned all the units... I then tried some sub-queries, but I am messing something up...

SELECT *
FROM bookingTable as q1 
WHERE (q1.unit = (SELECT unit FROM bookingTable AS q2 
                  WHERE q2.unit = q1.unit) 
       AND q1.checkIn = (SELECT checkIn FROM bookingTable AS q3)
      ) 
ORDER BY 
   q1.checkIn,q1.unit

ERROR:

Msg 512, Level 16, State 1, Line 2
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

¿Fue útil?

Solución

SELECT unit,checkIn,COUNT(*)
FROM bookingTable
GROUP BY unit,checkIn
HAVING COUNT(*) > 1

Will tell you which combination of unit and checkIn values appearing in more than one row.

If you want, you can then use this to see the individual rows:

SELECT bt.*
FROM bookingTable bt
INNER JOIN (
    SELECT unit,checkIn,COUNT(*) as cnt
    FROM bookingTable
    GROUP BY unit,checkIn
    HAVING COUNT(*) > 1
) t
 ON bt.unit = t.unit and
    bt.checkIn = t.checkIn
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top