SQL如何计算免费预订

时间:2016-12-14 08:12:18

标签: sql sql-server

我有2张桌子 保留

  • reservation no | trip ID |person ID| Status
  • 1 | 2 | 1 | C'
  • 2 | 3 | 2 | P'
  • 3 | 4 | 3 | P'
  • 4 | 1 | 4 | C'
  • 5 | 1 | 6 | P'
  • 6 | 1 | 7 | P'
  • 7 | 2 | 5 | P'

其中P代表付费,C代表取消

和旅行

  • trip ID |trip Name|Date | Free Places
  • 1 | Paris |2016-12-18| 5'
  • 2 | New York|2016-12-17| 6'
  • 3 | Warsaw |2016-12-15| 5'
  • 4 | London |2016-12-20| 10'

我想为每次旅行选择剩余免费名额

  • trip ID |trip Name|Date | Free Places | Left free Spaces
  • 1 | Paris |2016-12-18 | 5 | 3
  • 2 | New York| 2016-12-17 | 6 | 5
  • 3 | Warsaw |2016-12-15 | 5 | 4
  • 4 | London |2016-12-20 | 10 | 9

3 个答案:

答案 0 :(得分:1)

一种方法是使用预约表的子查询,该子查询计算每次旅行已经占用的空格数。然后将其连接回trips表以计算剩余空格数。

SELECT t1.tripID,
       t1.tripName,
       t1.Date,
       t1.FreePlaces,
       t1.FreePlaces - COALESCE(t2.numBooked, 0) AS left_free_spaces
FROM trips t1
LEFT JOIN
(
    SELECT tripID, SUM(CASE WHEN Status = 'P' THEN 1 ELSE 0 END) AS numBooked
    FROM Reservations
    GROUP BY tripID
) t2
    ON t1.tripID = t2.tripID

答案 1 :(得分:0)

试试这个代码。它可以帮助你

create table #RESERVATION (revservation_no bigint,trip_ID bigint,person_id bigint,status char(5))

insert into #RESERVATION values(1,2,1,'C'),(2,3,2,'P'),(3,4,3,'P'),(4,1,4,'C'),(5,1,6,'P'),(6,1,7,'P'),(7,2,5,'P')

CREATE TABLE #TRIP (TRIP_ID BIGINT,TRIP_NAME VARCHAR(50),DATE_ DATE ,FREE_PLACES BIGINT)

INSERT INTO #TRIP VALUES (1,'PARIS','2016-12-18',5),(2,'NEW YORK','2016-12-17',6),(3,'WARSAW','2016-12-15',5),(4,'LONDON','2016-12-20',10)

;WITH CTE AS(
SELECT DISTINCT T.TRIP_ID,T.TRIP_NAME,T.DATE_,T.FREE_PLACES,COUNT(revservation_no)AS LEFT_SPACES FROM #TRIP T
INNER JOIN #RESERVATION R ON R.trip_ID=T.TRIP_ID
WHERE status='P'
GROUP BY T.TRIP_ID,T.TRIP_NAME,T.DATE_,T.FREE_PLACES
)
SELECT TRIP_ID,TRIP_NAME,DATE_,FREE_PLACES,FREE_PLACES-LEFT_SPACES AS LEFT_FREE_PLACES  FROM CTE

答案 2 :(得分:0)

Select      D1.trip_ID ,trip_Name, [Date] , D1.Free_Places,
            D1.Free_Places - Sum(Case
                                    When D2.Status = 'P' then 1 
                                    Else 0
                                End) as Left_free_Spaces
From        Trips D1
Inner Join  Reservations D2
    On      D1.trip_ID = D2.trip_ID
Group by    D1.trip_ID ,trip_Name, [Date] , Free_Places