mysql嵌套查询问题

时间:2011-06-15 22:36:26

标签: mysql

我正在尝试设计一个mysql查询,以使用最新的trans_date和trans_count检索每个城市的行。我只希望每个城市返回一行。

表格交易

------------------
id = integer
trans_date = date
trans_city = varchar
trans_count = integer

样本数据

--------------
id       trans_date     trans_city     trans_count
--       ----------     ----------     -----------
1        2011-01-10     seattle        2104
2        2011-04-15     seattle        2072
3        2011-05-30     seattle        2057
4        2010-04-27     houston        5622
5        2010-04-30     houston        241
6        2010-05-25     houston        261

所需的查询结果(每个城市一行,包含该城市的最新日期和计数)

---------------------
id       trans_date     trans_city     trans_count
--       ----------     ----------     -----------
3        2011-05-30     seattle        2057
6        2010-05-25     houston        261

我找到的所有样本都没有返回我正在寻找的结果集。任何帮助表示赞赏。

谢谢,

-Scott

6 个答案:

答案 0 :(得分:3)

怎么样

SELECT * FROM 
  (
  SELECT id,trans_date,trans_city,trans_count 
  FROM transactions 
  ORDER BY trans_Date DESC) X 
GROUP BY trans_city 

我无法在其他答案上添加评论,但您需要嵌套,否则该组将在订单之前应用,并且不会给您预期的答案。

答案 1 :(得分:1)

SELECT id, 
       trans_date, 
       trans_city, 
       trans_count 
FROM YourTable 
GROUP BY trans_city
ORDER BY trans_date DESC, trans_count;

答案 2 :(得分:1)

这是一个适用于SQL Server的版本,仅仅是为了后人的缘故,因为upvoted解决方案没有。

SELECT
    t.*
FROM
    transactions AS t,
    (SELECT
        MAX(trans_date) AS max_date
    FROM
        transactions
    GROUP BY trans_city) AS subquery
WHERE
    subquery.max_date = t.trans_date

答案 3 :(得分:0)

SELECT DISTINCT `trans-city` 
FROM `table` 
ORDER BY `trans_date` DESC, `trans_count` DESC;

答案 4 :(得分:0)

with distinct_cities ( select max(id) as id, trans_city
from table
group by trans_city)

select t.id, t.trans_date, t.trans_city, t.trans_count
from table t join distinct_cities d on t.id = d.id

答案 5 :(得分:0)

从每个城市的最后一个日期的内部预查询开始..然后根据每个城市的最新条目加入

select t2.*
   from
      ( select t1.trans_city,
               max( t1.trans_date ) as MostRecentDate
           from 
               Transactions t1
           group by
               t1.trans_city ) PreQuery

      join Transactions t2
         on PreQuery.Trans_City = t2.Trans_City
         and PreQuery.MostRecentDate = t2.Trans_Date