我有一张这样的表
id name amount
1 fish 120
1 meat 230
2 meat 110
2 fish 78
1 salad 50
3 meat 103
3 salad 22
2 salad 34
我想编写一个查询,将对名称进行分组并对其数量进行求和,但它应该限制为前两个id,因此按名称对项目进行分组,并将每个匹配的名称相加...这应该将其限制为前两个id 。只是id 1和2。离开id 3.注意。 ID是另一个表中的外键。
这是我尝试过的。但它不起作用
select name, sum(amount) from table1 group by amount, id order by id limit 2
这只在计算后输出2个结果
name amount
fish 198
meat 443
我期待这样的事情
name amount
fish 198
meat 340
salad 84
添加ID为1和2的项目数量,并按名称对其进行分组
答案 0 :(得分:1)
select name, sum(amount)
from
(SELECT id, name, amount,
CASE WHEN @name=name THEN @rown:=@rown+1 ELSE @rown:=0 END as rn,
@name:=name
FROM table1, (select @rown:=0, @name:='') s
ORDER BY name, id
) sub
where rn<=1
group by name
输出
fish 198
meat 340
salad 84
答案 1 :(得分:0)
public class MyActivity extends Activity {
private AdView mAdView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
// Create a banner ad. The ad size and ad unit ID must be set before calling loadAd.
mAdView = new AdView(this);
mAdView.setAdSize(AdSize.SMART_BANNER);
mAdView.setAdUnitId("myAdUnitId");
// Create an ad request.
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
// Optionally populate the ad request builder.
adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
// Add the AdView to the view hierarchy.
layout.addView(mAdView);
// Start loading the ad.
mAdView.loadAd(adRequestBuilder.build());
setContentView(layout);
}
@Override
public void onResume() {
super.onResume();
// Resume the AdView.
mAdView.resume();
}
@Override
public void onPause() {
// Pause the AdView.
mAdView.pause();
super.onPause();
}
@Override
public void onDestroy() {
// Destroy the AdView.
mAdView.destroy();
super.onDestroy();
}
}
答案 2 :(得分:0)
您不希望限制总输出,但是您希望在它达到总和之前对其进行限制,以便您可以使用子查询。
select t1.name, sum(t1.amount)
from table1 t1 join
(select tt1.id
from table1 tt1
group by id
order by id
limit 2
) t2
on t1.id = t2.id
group by t1.name;
工作示例link
结果:
name sum(t1.amount)
fish 198
meat 340
salad 84
答案 3 :(得分:-1)
前两个ID是什么?如果我认为你的意思是&#34;全球&#34;,那么:
var get_price = "1,200";
var result = get_price.replace(/[,]+/g, "").trim();
console.log(result);
答案 4 :(得分:-1)
删除LIMIT
,仅GROUP BY
name
SELECT Name, SUM(amount) AS Amount
FROM table1
GROUP BY name
ORDER BY id
输出
Name Amount
fish 198
meat 443
salad 106
答案 5 :(得分:-2)
我认为你可以使用这样的东西:
SELECT B.NAME, SUM(B.AMOUNT) AS AMOUNT
FROM (
SELECT a.* ,
@r:= CASE WHEN @g = a.NAME THEN @r+1 ELSE 1 END consecutive,
@g:= a.NAME g
FROM DISHES a
CROSS JOIN (SELECT @g:='', @r:=1 ) t1
ORDER BY A.NAME, A.id
) B
WHERE B.consecutive<=2
GROUP BY B.NAME;
输出:
NAME AMOUNT
fish 198
meat 340
salad 84