0

我有区域,并且在这些区域内售出门票......我使用以下查询来获取每个区域售出的门票数量,并且我需要进行排序,以便可用区域(其中 count <容量)位于顶部排序:

SELECT z.name, z.capacity,count(t.ticketid) as thecount  
FROM tickets t JOIN zones z ON z.zoneid=t.zoneid 
GROUP BY z.name ORDER BY z.sortorder

返回:

+--------+----------+----------+
name cap thecount
+--------+----- -----+---------+
区域1 | 100 | 100
区2 | 300 | 300
区3 | 250 | 101
区4 | 600 | 522
区5 | 160 | 160
+--------+---------+----------+

我需要按以下顺序排序:
Zone3
Zone4
Zone1
Zone2
Zone5

我不确定如何使用表达式或其他东西来实现这一点——任何有用的提示?

4

3 回答 3

1
SELECT z.name, z.capacity,count(t.ticketid) as thecount   
FROM tickets t JOIN zones z ON z.zoneid=t.zoneid  
GROUP BY z.name  
order by case when thecount < c.capacity
              then thecount
              else c.capacity
         end
于 2012-05-25T21:49:15.643 回答
1
SELECT *, capacity - thecount AS availableSeats
FROM (
    SELECT z.name, z.capacity,count(t.ticketid) as thecount  
    FROM tickets t JOIN zones z ON z.zoneid=t.zoneid 
    GROUP BY z.name
) t
ORDER BY availableSeats, name

我想你可能还需要分组z.name, z.capacity

于 2012-05-25T22:10:03.673 回答
0

因此,根据 GWilliams00 的回答,我最终得到:

SELECT *, capacity < thecount AS availableSeats
FROM (
   SELECT z.name, z.capacity,count(t.ticketid) as thecount  
   FROM gt_tickets t JOIN gt_zones z ON z.zoneid=t.zoneid  
   GROUP BY z.name

) t
ORDER BY availableSeats,sortorder

'capacity < thecount' 评估为布尔值,因此可用于对可用区域进行排序,然后 sortorder 将它们保持在正确的名称顺序之后。

于 2012-05-25T23:12:11.393 回答