SELECT DISTINCT的子集

时间:2012-07-15 17:58:55

标签: sql

我有以下代码将具有最小和最大时间戳的行写入新表:

sql_sort_and_delete = """
                CREATE TABLE tmp AS
                SELECT DISTINCT * FROM c2g
                WHERE time = (SELECT max(time) FROM c2g)
                UNION SELECT DISTINCT * FROM c2g
                WHERE time = (SELECT min(time) FROM c2g);;"""

它工作正常,但c2g表中有不同城市的子集,我想更改代码,以便我得到每个城市的明显最小/最大结果。 是否有捷径可寻?谢谢!

4 个答案:

答案 0 :(得分:2)

可能会稍微复杂化某些事情,或者可能是使用CTE进行编码的有效方式:

SQL FIDDLE EXAMPLE

CREATE TABLE c2g 
    ( 
     CITY varchar(20), 
     TIME INT
    );

INSERT INTO c2g
(CITY, TIME)
VALUES
('A', 1),
('A', 2),
('B', 2),
('B', 2),
('B', 2),
('B', 2),
('C', 1),
('C', 2),
('C', 5),
('C', 20);

获取所需记录:

WITH CITY_cte(CITY, myMAX, myMIN)
AS
(
  SELECT
      CITY
      ,MAX(TIME) 
      ,MIN(TIME) 
  FROM c2g
  GROUP BY CITY
)
SELECT x.* 
FROM  
    c2g x
    INNER JOIN CITY_cte y
        ON x.CITY = y.CITY
WHERE 
  x.TIME = y.myMAX 
  OR
  x.TIME = y.myMIN 

答案 1 :(得分:1)

要获得每个城市的汇总MIN()/MAX(),请使用GROUP BY city。要从c2g中提取其余列,您需要INNER JOIN针对该城市和时间值的子查询SELECT DISTINCT c2g.* FROM c2g INNER JOIN (SELECT city, MAX(time) AS time FROM c2g GROUP BY city) maxtime ON c2g.city = maxtime.city AND c2g.time = maxtime.time UNION SELECT DISTINCT c2g.* FROM c2g INNER JOIN (SELECT city, MIN(time) AS time FROM c2g GROUP BY city) mintime ON c2g.city = mintime.city AND c2g.time = mintime.time

UNION

我认为通过在联接的OR条件中使用ON,可以简化此操作并且实际上无法使用SELECT DISTINCT c2g.* FROM c2g INNER JOIN (SELECT city, MAX(time) AS maxtime, MIN(time) AS mintime FROM c2g GROUP BY city) maxtime ON c2g.city = maxtime.city AND (c2g.time = maxtime.time OR c2g.time = maxtime.mintime)

{{1}}

答案 2 :(得分:1)

在大多数数据库中,您也可以通过执行以下操作来执行此操作:

select c.*
from (select cg.*,
             max(time) over (partition by city) as maxtime,
             min(time) over (partition by city) as mintime
      from c2g
     ) c
where time = maxtime or time = mintime

(这绝对不适用于mysql或Access,因为它们不支持Windows函数。)

答案 3 :(得分:-1)

SELECT City, MAX(Time)
FROM cg
GROUP BY City
UNION
SELECT City, MIN(Time)
FROM cg
GROUP BY City