CREATE TABLE Coins (Badge VARCHAr(10), Cointype INT, Number INT);
INSERT INTO Coins (Badge,Cointype, Number) VALUES
('' , 1, 1),
('' , 5, 2),
('' , 20, 3),
('' , 1, 4),
('' , 5, 5),
('' , 5, 6),
('' , 5, 7),
('RESET', 0 , 0),
('' , 1, 8),
('' , 10, 9),
('RESET', 0 , 0),
('' , 5, 10),
('' , 20, 11);
嗨,有了这张表,我希望在第一行('RESET',0,0)之上有以下总和
select
SUM(case when Cointype=1 Then Number else 0 END) as SUM1,
SUM(case when Cointype=5 Then Number else 0 END) as SUM5,
SUM(case when Cointype=20 Then Number else 0 END) as SUM20
from Coins
结果必须是这样的:
SUM1 SUM5 SUM20
5 20 3
这可能在MySql中吗?
在实际情况中,还有一个ID和时间戳字段。最高记录是具有最高ID和时间戳的最新记录。 因此,最新的记录必须汇总到RESET行。 (如果我们需要订购,可以使用ID或时间戳字段)
然后表格是这样的:
CREATE TABLE Coins (ID INT, Badge VARCHAr(10), Cointype INT, Number INT);
INSERT INTO Coins (ID, Badge,Cointype, Number) VALUES
(13,'' , 1, 1),
(12,'' , 5, 2),
(11,'' , 20, 3),
(10,'' , 1, 4),
(9,'' , 5, 5),
(8,'' , 5, 6),
(7,'' , 5, 7),
(6,'RESET', 0 , 0),
(5,'' , 1, 8),
(4,'' , 10, 9),
(3,'RESET', 0 , 0),
(2,'' , 5, 10),
(1,'' , 20, 11);
答案 0 :(得分:2)
如果您有自动数字列:
<强> SQL DEMO 强>
select
SUM(case when Cointype=1 Then Number else 0 END) as SUM1,
SUM(case when Cointype=5 Then Number else 0 END) as SUM5,
SUM(case when Cointype=20 Then Number else 0 END) as SUM20
from Coins
WHERE ID < ( SELECT MIN(ID)
FROM Coins
WHERE Badge = 'RESET' )
<强>输出强>
| SUM1 | SUM5 | SUM20 |
|------|------|-------|
| 5 | 20 | 3 |
修改强>
更改样本后,看起来行的顺序相反。然后,您需要MAX()
而不是MIN()
select
SUM(case when Cointype=1 Then Number else 0 END) as SUM1,
SUM(case when Cointype=5 Then Number else 0 END) as SUM5,
SUM(case when Cointype=20 Then Number else 0 END) as SUM20
from Coins
WHERE ID > ( SELECT MAX(ID)
FROM Coins
WHERE Badge = 'RESET' )