我之前从未使用过非规范化数据库,所以我会尽力解释我的问题。所以我有两张桌子:
customers表保存所有客户信息,orders表保存他们已下达的所有订单。我没有列出表格中的所有字段,只列出了我需要的字段。两个表中的客户编号都不是主键,但无论如何我都在内心加入。所以我遇到的问题是我不知道如何进行查询:
选择具有名字,姓氏和电子邮件的所有客户,并显示最新的订单日期,最近的总数和最近的订购类型。我知道我必须使用max()聚合作为日期,但这就是我所得到的。请帮助一个菜鸟。
答案 0 :(得分:3)
您可以尝试:
SELECT FirstName,
LastName,
Email,
OrderDate,
OrderTotal,
OrderType
FROM Customers AS C
INNER JOIN Order AS O
ON O.CustomerNumber = C.CustomerNumber AND
O.OrderDate = (
SELECT MAX (O1.OrderDate)
FROM Order AS O1
WHERE O1.CustomerNumber = C.CustomerNumber)
)
答案 1 :(得分:2)
假设Orders.OrderDate对于每个CustomerNumber都是唯一的,这对您有用吗?如果单个CustomerNumber在OrderDate订单中有多个条目,您将获得每个行。
select c.FirstName, c.LastName, c.Email, o.OrderDate, o.OrderTotal, o.OrderType
from Customers c
join
(select CusomterNumber, max(OrderDate) as MostRecentOrderDate
from Orders
group by CustomerNumber
) mro on mro.CustomerNumber=s.CustomerNumber
join Orders o on o.OrderDate=mro.MostRecentOrdeDate and
o.CustomerNumber=mro.CustomerNumber
答案 2 :(得分:0)
试试这个:
SELECT
Customers.*, Orders.*
FROM
Customers
JOIN
(SELECT
Customer_Number,
MAX(Order_Date) OrderDate
FROM
Orders
GROUP BY
Customer_Number
) as Ord ON Customers.Customer_Number = Ord.Customer_Number
JOIN Order ON Orders.Customer_Number = Ord.Customer_Number
答案 3 :(得分:0)
如果您使用SQL Server执行此操作,请使用查询设计器,基本上您只想做一个连接,因为您在Customer表中有两个相同的键 - >客户加入订单 - >客户将Customer表作为C和Orders表别名为O
所以例如
SELECT Customer.*, Orders.*
From Customer c, Orders O INNER JOIN O where C.Customer Number = O.Customer Number
这应该足以让你开始..如果你不想要所有字段然后完全限定名称,例如
SELECT C.FirstName, C.LastName, O.OrderDate, O.OrderType FROM Customer C, Orders O
WHERE C.Customer NUmber = O.Customer Number //this is another way of doing a Join when working with the where Clause.