【问题标题】:SQL order by DESC not workingDESC 的 SQL 顺序不起作用
【发布时间】:2014-06-10 15:03:21
【问题描述】:

我正在使用子查询进行相对较小的查询,我想按降序对子查询结果进行排序。但在结果中,子查询没有按降序排列。看不到 ORDER BY 对我不起作用的原因...

我的查询:

select 

customers.id,
customers.Name,
customers.Surname,

(select ifnull(sum(bets.amount),0)
from bets 
where customers.id=bets.customerId
and bets.date >'2014-06-01'
and bets.date <'2014-06-02'
order by bets.amount DESC
) as '1st_June',

(select ifnull(sum(bets.amount),0)
from bets 
where customers.id=bets.customerId
and bets.date >'2014-06-02'
and bets.date <'2014-06-03'
order by bets.amount DESC
) as '1st_June',


from customers

group by customers.id

我需要一个 DESC 订单,因为我想限制 100 个,所以我得到前 100 个值。有人可以建议一种方法吗...?

【问题讨论】:

  • 您想要每位客户的前 100 名投注吗?如果是这样,您使用的是什么数据库?
  • 或者.. 前 100 个投注金额值...和/或无论 6 月 1 日还是 6 月 2 日的最高投注?
  • 您的子查询按 desc 顺序排序。但是,您不能保证在连接两个查询后,结果会以相同的顺序显示。为什么不在最后按日期和金额对它们进行排序?

标签: sql


【解决方案1】:

Order By 不会像那样结转过去的 group by。

这应该会给你你正在寻找的东西:

SELECT customers.id
    ,customers.Name
    ,customers.Surname
    ,(
        SELECT ifnull(sum(bets.amount), 0)
        FROM bets
        WHERE customers.id = bets.customerId
            AND bets.date > '2014-06-01'
            AND bets.date < '2014-06-02'
        ) AS First_June
    ,(
        SELECT ifnull(sum(bets.amount), 0)
        FROM bets
        WHERE customers.id = bets.customerId
            AND bets.date > '2014-06-02'
            AND bets.date < '2014-06-03'
        ) AS Second_June
FROM customers
GROUP BY customers.id
ORDER BY First_June DESC
    ,Second_June DESC
LIMIT 100
  • 注意:(改为“First_June”。以数字开头的列名在多个 SQL Server 中存在问题,并且您没有指定您使用的是哪个。Oracle、MS SQL、MySql、Postgres 等)

【讨论】:

  • 请注意,arserbin3 将您的第二个子查询的别名从 First_June 更改为 Second_June,并将按第一个子查询然后第二个子查询对列表进行排序。
  • 感谢@Elias 澄清这一点。我认为这是基于日期范围的错字,并修复了它。
  • 它几乎可以工作,但有时订单之间有 0 个值
  • @user3669523 你能详细说明一下吗?我真的不明白你想说什么
  • @user3669523 按First_June 中的金额排序,然后按Second_June 中的金额排序。因此它将获取第二列的所有值,并按第一列的降序排列。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-02
  • 1970-01-01
  • 2011-06-08
  • 1970-01-01
相关资源
最近更新 更多