如何在mysql中使用2列进行分组

时间:2015-08-03 07:26:46

标签: mysql group-by

我在MySQL数据库中有一个查询

SELECT tbl_lab_reservations.full_desc, serial_number, rsvn_owner, reservation_id, 
SUM((SELECT DATEDIFF(reservation_date_end, reservation_date_start)+1)) AS totalNumberOfDaysReserve FROM tbl_lab_reservations 
JOIN tbl_lab_assets ON tbl_lab_assets.id = tbl_lab_reservations.lab_id 
WHERE tbl_lab_reservations.full_desc = 'WMHD (Masthead Amplifier)' 
AND tbl_lab_reservations.asset_status = 'Idle' 
GROUP BY rsvn_owner 
ORDER BY `tbl_lab_reservations`.`rsvn_owner` ASC

这是结果

query result

结果是正确的基于查询,但它不是我想要的。 根据我的数据保存在数据库上,应该有另一个名为PAYAK的rsvn_owner,但问题是PAYAK使用serial_numbers,IT也使用它,因为它按序列号{{1}分组PAYAK和IT的添加使它错了。 我想要的是查询按totalNumberOfDaysReserve分组,但如果它们属于不同的serial_number,则应创建另一行。

希望有人不赞成并能帮助我。提前致谢

1 个答案:

答案 0 :(得分:1)

所以只是尝试按序列号分组,然后由所有者分组? :)

GROUP BY serial_number, rsvn_owner
像这样

SELECT
  tbl_lab_reservations.full_desc, serial_number, rsvn_owner, reservation_id,
  SUM((SELECT DATEDIFF(reservation_date_end, reservation_date_start)+1)) AS totalNumberOfDaysReserve
FROM tbl_lab_reservations
JOIN tbl_lab_assets ON tbl_lab_assets.id = tbl_lab_reservations.lab_id
WHERE tbl_lab_reservations.full_desc = 'WMHD (Masthead Amplifier)'
  AND tbl_lab_reservations.asset_status = 'Idle'
GROUP BY serial_number, rsvn_owner
ORDER BY `tbl_lab_reservations`.`rsvn_owner`

AS语法告诉我们(请参阅逗号附近)

[GROUP BY {col_name | expr | position}
      [ASC | DESC], ... [WITH ROLLUP]]

我们可以这样做

https://dev.mysql.com/doc/refman/5.0/en/select.html