我正在尝试从我的数据库准备报告。
我有2个这样的表:
device sensor
id | name id | devid | value
====|===== ====|=======|========
1 | dev1 1 | 1 | 1.1
2 | dev2 2 | 1 | 1.2
3 | 2 | 2.1
4 | 2 | 2.2
我希望得到一个回报:
id | name | val_rc | val_cf
====|=======|===========|==========
1 | dev1 | 1.1 | 1.2
2 | dev2 | 2.1 | 2.2
我正在使用for语句将所有值都放入我的报告中。标题名称并不重要。
我尝试过这种SQL查询的不同排列:
SELECT device.id, device.name, sensor.value AS val_rc, sensor.value AS val_cf
FROM device
JOIN sensor
ON sensor.devid = device.id;
答案 0 :(得分:1)
您未提供有关如何确定每列中的值的详细信息,因此本示例使用row_number
:
select id,
name,
max(case when GROUP_ROW_NUMBER = 1 then value end) as val_rc,
max(case when GROUP_ROW_NUMBER = 2 then value end) as val_cf
from
(
select d.id, devid, name, value,
@num := if(@NAME = `NAME`, @num + 1, 1) as group_row_number,
@NAME := `NAME` as dummy
FROM device d
INNER JOIN sensor s
ON s.devid = d.id
order by name, value
) x
group by id, name
答案 1 :(得分:0)
您需要使用device
两次加入表格sensor
。
假设您希望rc
的值是表格中的第一个值,cf
是最后一个值,则此查询:
SELECT device.id, device.name, sensor1.value AS val_rc, sensor2.value AS val_cf
FROM device, sensor sensor1, sensor sensor2
where sensor1.devid= device.id
and sensor1.id = (select min(id) from sensor s1 where s1.devid= sensor1.devid)
and sensor2.devid= device.id
and sensor2.id = (select max(id) from sensor s2 where s2.devid= sensor2.devid)
将准确提供您的要求。
id | name | val_rc | val_cf
====|=======|===========|==========
1 | dev1 | 1.1 | 1.2
2 | dev2 | 2.1 | 2.2
答案 2 :(得分:0)
在看完你在这里写的是我想出的:
SELECT device.id, device.name,
(SELECT sensor.value FROM sensor WHERE sensor.devid = device.id AND sensor.senid = '1') AS val_rc,
(SELECT sensor.value FROM sensor WHERE sensor.devid = device.id AND sensor.senid = '2') AS val_cf
FROM device