表结构:
create table t_hr_ship (
shipment_id int,shipper_id int,date_time date,pickup_state varchar(20),dropoff_state varchar(20));
此表中有一些数据:
insert into t_hr_ship values
(1,1,"2018-01-01","WA","OR"),(2,"2018-01-02",(3,"2018-01-03",(4,"2018-01-04",(5,2,"2018-01-05",(6,3,"2018-01-06",(7,"2018-02-01","OR","WA"),(8,4,"2018-02-02",(9,"2018-02-03","CA"),(10,5,"2018-02-04","CA",(11,"2018-03-05","TX"),(12,"CA");
问题是要获得1月和2月的前3条最繁忙的路线。请注意,“ WA”到“ OR”和“ OR”到“ WA”的路线是相同的(两个端点的顺序无关紧要(只要它们的两个末端端口相同)。 解决方法如下:
select case when s.pickup_state < s.dropoff_state then s.pickup_state else s.dropoff_state end as pickup,case when s.pickup_state > s.dropoff_state then s.pickup_state else s.dropoff_state end as dropoff,count(s.shipment_id) as no_of_shipment
from t_hr_ship s
where month(s.date_time) in ("01","02")
group by pickup,dropoff
order by no_of_shipment desc
limit 3;
这确实达到了我的期望。我的问题是:我从在线资源中得知,SQL查询的执行顺序是from -> where -> group -> having -> select -> order by -> limit",if this is true than this solution should not work because the
提取and
下降defined in
选择can't be used in
分组依据。我错过了什么吗?