Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
d473566
Starting Member
23 Posts |
Posted - 2004-11-09 : 14:10:40
|
| HiI have a table that looks like the following:ID | BookingNum | inventAction | ---------------------------------1 | 10 | booked2 | 10 | booked3 | 10 | booked4 | 10 | unbooked5 | 10 | unbooked6 | 20 | booked7 | 20 | booked8 | 20 | unbooked9 | 30 | booked10 | 30 | unbookedetc.What I want is a recordset that will look like:BookingNum | Booked | Unbooked--------------------------------------------10 | 3 | 2 20 | 2 | 1 30 | 1 | 1 I thought the following would do it, but it doesn't seem to work. (Instead of counting the number booked/unbooked for a particular booking number, it counts ALL the booked/unbooked in the table). It is close to what I am looking for, so I *think* I am close to getting it!SELECT FlightAllocationHist.bookingNum ,booked = (SELECT COUNT(*) FROM FlightAllocationHist WHERE bookingNum = FlightAllocationHist.bookingNum AND inventAction = 'booking') ,unbooked = (SELECT COUNT(*) FROM FlightAllocationHist WHERE bookingNum = FlightAllocationHist.bookingNum AND inventAction = 'unbooking') FROM FlightAllocationHistGROUP BY FlightAllocationHist.bookingNumThanks in advance.... |
|
|
d473566
Starting Member
23 Posts |
Posted - 2004-11-09 : 14:13:52
|
| OK, solved it right after I posted. I had to alias the subqueries...SELECT FlightAllocationHist.bookingNum ,booked = (SELECT COUNT(*) FROM FlightAllocationHist b WHERE b.bookingNum = FlightAllocationHist.bookingNum AND inventAction = 'booking') ,unbooked = (SELECT COUNT(*) FROM FlightAllocationHist c WHERE c.bookingNum = FlightAllocationHist.bookingNum AND inventAction = 'unbooking') FROM FlightAllocationHistGROUP BY FlightAllocationHist.bookingNum |
 |
|
|
amachanic
SQL Server MVP
169 Posts |
Posted - 2004-11-09 : 14:30:26
|
| This should do it more efficiently:SELECT BookingNum,SUM(CASE inventAction WHEN 'booked' THEN 1 ELSE 0 END) AS Booked,SUM(CASE inventAction WHEN 'unbooked' THEN 1 ELSE 0 END) AS UnbookedFROM FlightAllocationHistGROUP BY BookingNum |
 |
|
|
|
|
|