0

我需要从有 2 个主键 macid 和 deviceid 的表中选择数据。

我需要记录集按这两个主键对记录进行分组,但我不知道该怎么做。

这就是我现在所拥有的:

SELECT * FROM data WHERE stamp > 1373040000000 AND stamp < 1373126400000 ORDER BY macid ASC,deviceid ASC,stamp ASC

[
{"deviceid":1,"temp":-19.81,"macid":"19:5d:ee3e00","stamp":1373054400000},
{"deviceid":1,"temp":-20.31,"macid":"19:5d:ee3e00","stamp":1373065200000},
{"deviceid":3,"temp":28.87,"macid":"19:5d:ee3e00","stamp":1373054400000},
{"deviceid":3,"temp":28.87,"macid":"19:5d:ee3e00","stamp":1373065200000}
]

这就是我需要的

[
[{"deviceid":1,"temp":-19.81,"macid":"19:5d:ee3e00","stamp":1373054400000},
{"deviceid":1,"temp":-20.31,"macid":"19:5d:ee3e00","stamp":1373065200000}]

[{"deviceid":3,"temp":28.87,"macid":"19:5d:ee3e00","stamp":1373054400000},
{"deviceid":3,"temp":28.87,"macid":"19:5d:ee3e00","stamp":1373065200000}]
]

我已经尝试过了,但它只返回与第一个结果相同的结果:

SELECT * FROM data WHERE stamp > 1373040000000 AND stamp < 1373126400000 GROUP BY macid, deviceid, stamp ORDER BY macid ASC,deviceid ASC,stamp ASC

这可能吗 ??

4

1 回答 1

0

实际上,您不能让 SQL 服务器返回多组行。GROUP BY语句用于按某些列对行进行分组,并为其他列计算聚合函数(行数、总和、平均值等)。结果,每组只返回一行。

所以,我认为我们需要在客户端进行分组。您可以按以下方式执行此操作:

var devices=[
{"deviceid":1,"temp":-19.81,"macid":"19:5d:ee3e00","stamp":1373054400000},
{"deviceid":1,"temp":-20.31,"macid":"19:5d:ee3e00","stamp":1373065200000},
{"deviceid":3,"temp":28.87,"macid":"19:5d:ee3e00","stamp":1373054400000},
{"deviceid":3,"temp":28.87,"macid":"19:5d:ee3e00","stamp":1373065200000}
];

var devicesGrouped = {};
for (i=0; i < devices.length; i++) 
{
   key = [devices[i].deviceid, devices[i].macid];
   if (!(key in devicesGrouped))
      devicesGrouped[key] = [];

   devicesGrouped[key].push(devices[i]);
}

结果将被用作键的devicesGrouped散列:[deviceid,macid]

{"1,19:5d:ee3e00":
     [{"deviceid":1,"temp":-19.81,"macid":"19:5d:ee3e00","stamp":1373054400000},
      {"deviceid":1,"temp":-20.31,"macid":"19:5d:ee3e00","stamp":1373065200000}],

 "3,19:5d:ee3e00":
     [{"deviceid":3,"temp":28.87,"macid":"19:5d:ee3e00","stamp":1373054400000},
      {"deviceid":3,"temp":28.87,"macid":"19:5d:ee3e00","stamp":1373065200000}]
}
于 2013-07-07T00:31:09.433 回答