0

我正在尝试从我的数据库中准备一份报告。

我有两张这样的桌子:

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;
4

3 回答 3

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

请参阅带有演示的 SQL Fiddle

于 2012-10-03T20:34:24.640 回答
0

您需要使用 加入表device两次sensor

假设您希望 forrc的值是表中的第一个值和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
于 2012-10-03T20:47:31.303 回答
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
于 2012-10-03T21:06:08.030 回答