首页 > 解决方案 > 如何将具有不同值但名称相同的主键分组并使用 datediff

问题描述

所以我有三张桌子:

客人可以进行预订,在预订表中,您可以根据主键“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           |

标签: mysqlsql

解决方案


修复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.


推荐阅读