我需要从有两个主键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
这可能吗?
答案 0 :(得分: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}]
}