我是MYSQL的新手。我有一个MYSQL表' MACTrain'。该表看起来像这样:
+------+-------+-------+-------+-------+
| id | RSSI1 | RSSI2 | RSSI3 | RSSI4 |
+------+-------+-------+-------+-------+
| 1 | -74 | -39 | -68 | -57 |
| 2 | -74 | -43 | -60 | -60 |
| 3 | -75 | -37 | -55 | -59 |
| 4 | -75 | -39 | -52 | -58 |
| 5 | -74 | -39 | -54 | -75 |
| 6 | -71 | -38 | -56 | -73 |
| 7 | -72 | -39 | -60 | -55 |
| 8 | -70 | -37 | -66 | -54 |
| 9 | -76 | -40 | -65 | -57 |
| 10 | -68 | -40 | -60 | -52 |
+------+-------+-------+-------+-------+
我正在尝试编写一个查询,它将显示从id(1到2),(3到4),(4到6),(6到8),(8到10)满足的值的数量以下表达式RSSI1< RSSI2,RSSI2< RSSI3,RSSI3< RSSI4,RSSI4< RSSI1。
因此,例如,结果应如下所示:
(FOR ID 1 to 2)2 0 1 0
(FOR ID 3 to 4)3 0 0 0
(FOR ID 4 to 6)3 0 0 2
(FOR ID 6 to 8)3 0 2 1
(FOR ID 8 to 10)3 0 3 0
我使用游标在MYSQL中编写了一个基本过程,它针对固定的id范围执行以下操作:
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE RSSI1_RSSI2 INTEGER;
DECLARE RSSI2_RSSI3 INTEGER;
DECLARE RSSI3_RSSI4 INTEGER;
DECLARE RSSI4_RSSI1 INTEGER;
DECLARE curs1 CURSOR FOR (SELECT COUNT(*) FROM MACTrain where id between 6 and 8 and RSSI1<RSSI2)
union (SELECT COUNT(*) FROM MACTrain where id between 6 and 8 and RSSI2<RSSI3)
union (SELECT COUNT(*) FROM MACTrain where ID between 6 and 8 and RSSI3<RSSI4)
union (SELECT COUNT(*) FROM MACTrain where ID between 6 and 8 and RSSI4<RSSI1);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN curs1;
read_loop: LOOP
FETCH curs1 INTO RSSI1_RSSI2;
IF done THEN
LEAVE read_loop;
END IF;
SELECT RSSI1_RSSI2;
END LOOP;
CLOSE curs1;
END
我可以为此硬编码范围获得正确的值。但是我有一些问题。结果显示为:
+-------------+
| RSSI1_RSSI2 |
+-------------+
| 3 |
+-------------+
1 row in set (0.01 sec)
+-------------+
| RSSI1_RSSI2 |
+-------------+
| 0 |
+-------------+
1 row in set (0.01 sec)
+-------------+
| RSSI1_RSSI2 |
+-------------+
| 2 |
+-------------+
1 row in set (0.01 sec)
+-------------+
| RSSI1_RSSI2 |
+-------------+
| 1 |
+-------------+
1 row in set (0.01 sec)
那是我得到4个单独的行。我希望结果看起来像:
3 0 2 1
i-e 1行4列。现在我得到4个单独的行和1列。
我尝试在我的FETCH语句中使用变量RSSI2_RSSI3,RSSI3_RSSI4和RSSI4_RSSI1。但是我得到错误的错误获取变量数。所以我想知道如何在这里解决2个问题:
1)我需要查询从id的id(1到2),(3到4),(4到6),(6到8),(8到10)动态地进行这些分析。我是否需要有一个ids的表达式,所以我不对该范围进行硬编码?
2)如何将结果显示为获取值的1行。
我真的很感激可以提供任何帮助。
答案 0 :(得分:1)
单个group by
怎么样?
select (case when id between 1 and 2 then '1-2'
when id between 3 and 4 then '3-4'
when id between 6 and 8 then '6-8'
else '9-10'
end) as thegroup,
SUM(RSSI1 < RSSI2),
SUM(RSSI2 < RSSI3),
SUM(RSSI3 < RSSI4),
SUM(RSSI4 < RSSI1)
from MACTrain
group by (case when id between 1 and 2 then '1-2'
when id between 3 and 4 then '3-4'
when id between 6 and 8 then '6-8'
else '9-10'
end);