[英]How group primary keys with different value but same name and using datediff
So I have three tables: 所以我有三个表:
Guest can make a reservation and in the reservation table you can see what kind of reservation the guest made based on the primary key 'pID'. 来宾可以进行预订,并且您可以在预订表中根据主键“ pID”查看来宾进行了哪种预订。 I want to show only the reservation of luxe rooms and the amount of days the guest spends there. 我只想显示豪华客房的预订以及客人在那儿度过的天数。 I don't even know what I am doing is the right way. 我什至不知道我在做什么是正确的方法。 I hope someone can help me. 我希望有一个人可以帮助我。
reservation: 保留:
pID |begindate | enddate |
------------------------------------------------------
COD12 | 2014-07-15 | 2014-07-18 |
COD400 | 2014-07-20 | 2014-07-21 |
KOD12 | 2014-07-01 | 2014-07-07 |
Luxe room table: 豪华房桌:
pID |city |
---------------------------------
COD12 | Corona |
COD400 | Corona |
KOD12 | Kentucky |
Small room table:
pID |city |
---------------------------------
COD600 | Corona |
MOD10 | Madrid |
KOD20 | Kentucky |
What I want: Amount of days spent from guest in Luxe rooms, note that Corona has two rooms: 我想要的是:在豪华客房中待客的天数,请注意,Corona有两个房间:
city |amountofdays |
---------------------------------
Corona | 4 |
Kentucky | 6 |
What I tried to do: 我试图做的是:
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 |
Fix the group by
: group by
以下方式固定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;
You want one room per city, so the GROUP BY
should only include city
. 您想要每个城市一个房间,因此GROUP BY
应该只包括city
。
You need group by and sum 您需要分组和求和
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.