mysql查询获取SUM()具体行?

时间:2016-12-06 23:12:34

标签: mysql sql

是否可以使用SUM来获取查询中的特定行? 例如:

id  tickets 
1   10          1-10        10=10
2   35          11-45       10+35=45
3   45          46-90       10+35+45=90
4   110         91-200      10+35+45+110=200

总计:200张票(在SUM中),我需要获得行号,其票号为23(输出为ID:2,因为ID:2在SUM中包含11-45个票)

3 个答案:

答案 0 :(得分:1)

您可以通过在select查询(form子句中)中定义局部变量来实现,例如:

select id, @total := @total + tickets as seats
from test, (select @total := 0) t

以下是 SQL Fiddle

答案 1 :(得分:0)

SELECT
  d.id
  ,d.tickets
  ,CONCAT(
      TRIM(CAST(d.RunningTotal - d.tickets + 1 AS CHAR(10)))
      ,'-'
      ,TRIM(CAST(d.RunningTotal AS CHAR(10)))
  ) as TicketRange
  ,d.RunningTotal
FROM
  (
    SELECT
       id
       ,tickets
       ,@total := @total + tickets as RunningTotal
    FROM
      test
      CROSS JOIN (select @total := 0) var
    ORDER BY
      id
   ) d

这与Darshan's answer类似,但有一些主要区别:

  • 您不应该使用隐式连接语法,显式连接从长远来看具有更多功能,并且已经超过20年的标准
  • 使用变量计算时,
  • ORDER BY会对您的运行总计产生巨大影响!如果您更改订单,它将以不同的方式计算,因此您需要考虑如何按日期执行运行总计?通过id?通过???并确保将其放入查询中。
  • 最后我实际上也计算了范围。

以下是不使用变量的方法:

SELECT
  d.id
  ,d.tickets
  ,CONCAT(
      TRIM(d.LowRange)
      ,'-'
      ,TRIM(
          CAST(RunningTotal AS CHAR(10))
        )
    ) as TicketRange
  ,d.RunningTotal
FROM
  (
    SELECT
      t.id
      ,t.tickets
      ,CAST(COALESCE(SUM(t2.tickets),0) + 1 AS CHAR(10)) as LowRange
      ,t.tickets + COALESCE(SUM(t2.tickets),0) as RunningTotal
    FROM
      test t
      LEFT JOIN test t2
      ON t.id > t2. id
    GROUP BY
      t.id
      ,t.tickets
   ) d

答案 2 :(得分:0)

你似乎想要“23”适合的行。我认为这样做的诀窍:

select t.*
from (select t.*, (@total := @total + tickets) as running_total
      from t cross join
           (select @total := 0) params
      order by id
     ) t
where 23 > running_total - tickets and 23 <= running_total;