如何将具有不同值但名称相同且使用datediff的主键分组

时间:2019-06-24 15:49:18

标签: mysql sql

所以我有三个表:

客人可以进行预订,您可以在预订表中看到客人基于主键“ pID”进行的预订。我只想显示豪华客房的预订以及客人在那儿度过的天数。我什至不知道我在做什么是正确的方法。我希望有人能帮助我。

预订:

pID              |begindate    | enddate     |   
------------------------------------------------------
COD12            | 2014-07-15  | 2014-07-18  |
COD400           | 2014-07-20  | 2014-07-21  |
KOD12            | 2014-07-01  | 2014-07-07  |

豪华房桌:


pID              |city         |    
---------------------------------
COD12            | Corona      | 
COD400           | Corona      | 
KOD12            | Kentucky    | 

Small room table:

pID              |city         |    
---------------------------------
COD600           | Corona      |
MOD10            | Madrid      |
KOD20            | Kentucky    | 

我想要什么: 在豪华客房中待客的天数,请注意,Corona有两个房间:

city             |amountofdays |    
---------------------------------
Corona           | 4           |
Kentucky         | 6           |


我试图做的事情

SELECT datediff(reservation.enddate,reservation.begindate) as amountofdays, luxeroom.city FROM reservation
INNER JOIN luxeroom ON reservation.pID = luxeroom.pID
GROUP BY luxeroom.pID, luxeroom.city; 

this resulted in:

city             |amountofdays |    
---------------------------------
Corona           | 3           |
Corona           | 1           |
Kentucky         | 6           |

2 个答案:

答案 0 :(得分:1)

修复group by

SELECT sum(datediff(r.enddate, r.begindate)) as amountofdays, l.city
FROM reservation r JOIN
     luxeroom l
     ON r.pID = l.pID
GROUP BY l.city; 

您想要每个城市一个房间,因此GROUP BY仅应包含city

答案 1 :(得分:1)

您需要分组和求和

SELECT sum(datediff(a.enddate, a.begindate)) as amountofdays, b.city
FROM reservation a 
JOIN luxeroom b  ON a.pID = b.pID
GROUP BY b.city;