SQL查询问题

时间:2017-11-29 02:24:54

标签: sql database

所以我是这个网站的新手,因为我刚刚开始了一个基于数据的课程,所以我还在学习基础知识,但我需要一些帮助。所以这就是我遇到的两个问题。

2015年3月1日入住的所有公寓的清单,按复杂和公寓编号分类。示例结果:

complexName apartmentNumber
Fox Run      101
Fox Run      102
Fox Run      204
Oak Meadows  103
Villa Maria  11
Villa Maria  12

2015年3月1日当前租约的所有租户列表,按房产和公寓编号排序 示例结果:

complexName apartmentNumber givenName   familyName
Fox Run      101             Shannon    McCoy
Fox Run      102             Larry      Thomas
Fox Run      204             Mark       Patterson
Oak Meadows  103             Jose       Ortiz
Villa Maria  11              Cassie     Lee
Villa Maria  12              Robert     Woodward

我的SQL第一个问题是......

SELECT DISTINCT name AS 'complexName', number AS 'apartmentNumber'
FROM week9wildwood.Complex AS c
INNER JOIN week9wildwood.Apartment AS a ON c.complexID = a.Complex_complexID
INNER JOIN week9wildwood.Lease AS l ON a.number = l.Apartment_number
WHERE startDate BETWEEN '2015-03-01' AND '2016-03-01'
ORDER BY name, number;

但我一直回来......

complexName apartmentNumber
Fox Run      102
Fox Run      103
Fox Run      104
Oak Meadows  102
Oak Meadows  103
Villa Maria  11
Villa Maria  21

我不确定我做错了什么,以及为什么它会以不同的数据回来。我也觉得第一个问题的疑问,对于第二个问题几乎是一样的,但它的措辞让我犹豫不决。任何建议将不胜感激!

1 个答案:

答案 0 :(得分:-1)

你试过Group By吗?

SELECT DISTINCT name AS 'complexName', number AS 'apartmentNumber' 
FROM week9wildwood.Complex c 
INNER JOIN week9wildwood.Apartment a
ON c.complexID = a.Complex_complexID 
INNER JOIN week9wildwood.Lease l 
ON a.number = l.Apartment_number 
WHERE startDate BETWEEN '2015-03-01' AND '2016-03-01' 
GROUP BY 1
ORDER BY name, number;