3

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

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

4 回答 4

2

Maybe over complicating things slightly or maybe a valid way of coding this with 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);

To get required records:

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 
于 2012-07-15T21:25:36.640 回答
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使用 an来工作:ORON

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)
于 2012-07-15T18:05:22.407 回答
1

在大多数数据库中,您还可以使用 Windows 函数执行此操作,方法如下:

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 功能。)

于 2012-07-15T19:34:04.787 回答
-1
SELECT City, MAX(Time)
FROM cg
GROUP BY City
UNION
SELECT City, MIN(Time)
FROM cg
GROUP BY City
于 2012-07-15T23:03:37.773 回答