我是学习SQL的初学者。我的代码可能很粗糙。我有2张桌子。试图得到没有。自交易表中每一行开设帐户以来的天数。我使用的代码不断给我一个错误。
表1:Orders
Customer_Id TxnDate Amount
-------------------------------
4001 21-Aug-18 245.99
4002 30-Jan-18 49.99
4003 15-Apr-17 204.87
4001 18-Dec-18 130.88
4004 15-May-17 198.33
4006 4-Feb-17 783.65
表2:Customers
Customer_Id AcctOpenDate CustomerFirstName CustomerLastName
--------------------------------------------------------------
4001 7-Jan-16 John Doe
4002 15-Apr-15 Ashley Smith
4003 14-May-14 Carter Jones
4004 17-Sep-16 Ika Gaut
4005 18-Aug-14 Gray Show
4006 25-Oct-15 Kathia Kim
查询:
SELECT c.Customer_Id, c.AcctOpenDate, c.CustomerFirstName, c.CustomerLastName
FROM dbo.Customers
LEFT OUTER JOIN Orders ON Orders.Customer_Id = Customers.Customer_Id;
SELECT DATEDIFF (d, "AcctOpenDate", "TxnDate") AS Dayssinceacctopen
FROM dbo.Orders;
当前产生的错误:
消息208,第16级,状态1,第26行
无效的对象名称'dbo.Customers'
答案 0 :(得分:0)
要返回这两个日期之间的差,可以使用以下查询:
SELECT c.Customer_Id, c.AcctOpenDate, c.CustomerFirstName, c.CustomerLastName,
DATEDIFF(day, c.AcctOpenDate, o.TxnDate) AS DaysSinceAcctOpen
FROM Customers c
LEFT OUTER JOIN Orders o ON o.Customer_Id = c.Customer_Id;
我为“客户”表设置了别名,因为您在结果字段名称上使用了“ c”别名。
此查询是否还会引发相同的错误,即对象名称无效的客户?
答案 1 :(得分:0)
正如评论中确认的那样,您需要在表订单上附加一个名为Dayssinceacctopen的附加列,我认为您可以在表订单和客户之间使用INNER JOIN来获得所需的结果集,如下所示-
SELECT
C.Customer_Id,
C.AcctOpenDate,
C.CustomerFirstName,
C.CustomerLastName,
O.TxnDate,
O.Amount,
DATEDIFF(DD,C.AcctOpenDate,O.TxnDate) Dayssinceacctopen
FROM Orders O
INNER JOIN Customers C ON O.Customer_Id = C.Customer_Id