在块中的WHERE语句之间使用UNION ALL? GROUP BY错误

时间:2019-06-27 08:45:24

标签: sql

我的代码中的此错误有些麻烦。

Expected tokens [EOF]. Found token [GROUP] (Line: 61, Column: 1)

我要做的就是查询所有语句之间的并集。我的代码看起来像这样。

Select vehicles,
SUM(passengers) 
FROM 

(
  SELECT 
  "Toyota" As vehicles,
      count(distinct uid) As passengers
        FROM vehicle_table_1
        WHERE timestamp > '2018-12-31 23:59:59' AND model in ('Land Cruiser','C-HR')

UNION ALL

(SELECT
  "Land Rover" As vehicles,
     COUNT (DISTINCT uid) As passengers
        FROM vehicle_table_2
        WHERE timestamp > '2018-12-31 23:59:59') 

UNION ALL

(SELECT 
  "Jeep" As vehicles,
    count(distinct uid) As passengers
      FROM  vehicle_table_3
      WHERE submitted_timestamp > '2018-12-31 23:59:59')

GROUP BY 1

为什么我会错误地得到这个小组?在这些块中不可能有where语句?任何帮助表示赞赏。谢谢!

2 个答案:

答案 0 :(得分:1)

您应将联合放在自己的子查询中:

Select  vehicles,
        SUM(passengers) 
FROM    (
         SELECT "Toyota" As vehicles,
                count(distinct uid) As passengers
         FROM   vehicle_table_1
         WHERE  timestamp > '2018-12-31 23:59:59' AND model in ('Land Cruiser','C-HR')

        UNION ALL

        SELECT   "Land Rover" As vehicles,
                 COUNT (DISTINCT uid) As passengers
        FROM     vehicle_table_2
        WHERE    timestamp > '2018-12-31 23:59:59'

        UNION ALL

        SELECT "Jeep" As vehicles,
               count(distinct uid) As passengers
        FROM   vehicle_table_3
        WHERE  submitted_timestamp > '2018-12-31 23:59:59'
    ) AS sel

GROUP BY vehicles

答案 1 :(得分:1)

您不需要GROUP BY。您的子查询已经是单独的行。您还可以简化日期比较:

select 'Toyota' As vehicles,
       count(distinct uid) as passengers
from vehicle_table_1
where timestamp >= '2019-01-01' and
      model in ('Land Cruiser', 'C-HR')
union all
select 'Land Rover' As vehicles,
       count(distinct uid) As passengers
from vehicle_table_2
where timestamp >= '2019-01-01'
union all
select 'Jeep' As vehicles,
       count(distinct uid) As passengers
from vehicle_table_3
where submitted_timestamp > '2019-01-01';

如果要控制最终结果集的顺序,请使用order by vehicles