我有一张表:
from |to|quani
A1 |A2|200
B1 |B2|200
C1 |C2|210
D1 |D2|210
E1 |E2|220
F1 |F2|220
G1 |G2|220
H1 |H2|200
J1 |J2|200
我需要一个查询或脚本来获得这样的东西:
from|to|quani
A1 |B2|200
C1 |D2|210
E1 |G2|220
H1 |J2|200
如果我使用GROUP BY quani
,则会选择
from|to|quani
A1 |A2|200
C1 |C2|210
E1 |E2|220
答案 0 :(得分:2)
似乎你需要min来为quani分组的值
select min(from), min(to), quani
from my_table
group by quani
答案 1 :(得分:1)
尝试以下查询:
select min(temp.from_) as from_,
max(temp.to_) as to_,
temp.quani as quani
from
(SELECT t.*,
(case when @prev = quani
then @rowid
else @rowid:=@rowid+1
end
) as rowid,
@prev:= quani as prev
FROM t, (SELECT @rowid:=0,@prev:=1) as init
ORDER BY from_) as temp
group by temp.quani,temp.rowid;
答案 2 :(得分:0)
假设您可以按第一列排序,则需要quani
更改的行。一种方法使用变量。以下是使用相关子查询的另一种方法:
select t.*,
(select t2.to
from t t2
where t2.to < t.to
order by t2.to desc
limit 1
) as prev_to
from t
having prev_to is null or prev_to <> to;
注意:
(to, quani)
上的索引可以提供帮助。to
和from
是SQL关键字,因此它们是列的非常糟糕的名称。having
是一个MySQL扩展,允许按列别名进行过滤(没有子查询)。where not prev_to <=> to
,但NULL
- 安全运算符不仅仅是<>
。