【问题标题】:Usage of Group By and Order By in MysqlMysql中Group By和Order By的使用
【发布时间】:2013-09-06 06:57:44
【问题描述】:

我尝试读取的表格

这里我正在尝试读取具有最新 TransactionDate 并按 StackHistoryID 分组的行。

所以我想首先使用“order by TransactionDate desc”,然后最新的行将位于顶部,如果我在之后使用 group by,它将给出我想要的。但我想,我们不能在使用 orderby 后使用 groupby。所以我来到这里,有什么方法可以使用单个查询来获得我想要的东西。

更新:

select ID, Max(TransactionDate) from Stacks group by StackHistoryID

但是这个输出中第一行的 ID 应该是 9。

【问题讨论】:

  • ID 不是“ID”,而是 StackHistoryID,它是您分组的内容。输出是正确的。

标签: mysql group-by sql-order-by


【解决方案1】:

See SQLFiddle

使用 MAX()

select StackHistoryID, Max(TransactionDate)
from Stacks
group by StackHistoryID;

还有带ID的简单查询,使用MAX; (如果 ID 是增量的,即更高的 id 不能有更低的日期):

select Max(ID),StackHistoryID, Max(TransactionDate)
from Stacks
group by StackHistoryID;

如果您的 ID 不是与日期一起递增的,即您可以有一个较高的 ID 较低的日期...然后您可以执行以下操作:

select alls.ID, s.StackHistoryID, s.TransactionDate
from
(
  select StackHistoryID as StackHistoryID, 
         Max(TransactionDate) as TransactionDate
  from stacks
  group by StackHistoryID desc 
) s, Stacks alls
where
  alls.StackHistoryID = s.StackHistoryID
  and
  alls.TransactionDate = s.TransactionDate
order by StackHistoryID
;

See SQLFiddle

【讨论】:

  • 我更愿意明确地使用JOIN,但我同意其他所有内容。
【解决方案2】:

如果您希望对 stackhistoryidtransactiondate 的所有数据进行排序。那就去吧。

select * from stacks order by StackHistoryID, TransactionDate desc;

如果您只需要最新日期,请查看@MrSimpleMind 指定的结果

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-22
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    相关资源
    最近更新 更多