2016-12-06 66 views
0

是否有可能使用像SUM查询中的特定行? 例子:Mysql查询获取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(输出将是ID:2,因为ID:2包含SUM 11-45tickets )

回答

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; 
+0

谢谢你,我正在寻找什么。 :) –

1

您可以通过定义一个局部变量到您的select查询(在form条款做到这一点),例如:

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

这里是SQL Fiddle

+0

'select id,@ total + 1 as the minimum,@total:= @total +票据最高 from test,(select @total:= 0)t'会给出您可以查询的范围。之间。 –

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