SQL列出问题

时间:2018-02-24 04:39:26

标签: sql sql-server

我有这个问题的功课,我无法让它工作。这是问题:

  

使用相关子查询为每个客户返回一行代表   客户的最新订单(具有最新日期的订单)   销售税金额大于100美元。每行应包括   这四列:EmailAddress,OrderID,OrderDate和TaxAmount。

这是我的代码:

SELECT  EmailAddress, OrderID, TaxAmount, OrderDate AS LatestOrder
  FROM  Customers AS C
        JOIN Orders AS O1
            ON C.CustomerID = O1.CustomerID
 WHERE  (O1.OrderDate =
            (SELECT MAX(OrderDate)
             FROM Orders AS O2
             WHERE C.CustomerID = O2.CustomerID)) and TaxAmount > 100

结果对我来说似乎有些偏差。有人可以帮帮我吗?非常感谢你

4 个答案:

答案 0 :(得分:1)

此查询中有三个联接。第一个选择客户(C),加入一个 订单上的子查询,获取每个有税收的客户的最新订单日期 大于100(LastOrd),然后使用此信息再次加入订单 表并获取最新订单(Ord)的关联数据。在这个例子中, 第二个查询将保证每个客户的单个订单:

请注意,select语句中的Email来自Customer表,OrderId和TaxAmount来自实际的Orders表,而LatestOrder来自子查询“LastOrd”。

SELECT  C.EmailAddress, 
        Ord.OrderID, 
        LastOrd.LatestOrder
        Ord.TaxAmount, 
FROM  Customers AS C
INNER JOIN (SELECT CustomerID, 
                   MAX(OrderDate) LatestOrder
            FROM Orders
            WHERE TaxAmount > 100
            GROUP BY CustomerID) AS LastOrd
    ON  C.CustomerID = LastOrd.CustomerID
INNER JOIN Orders Ord
    ON  LastOrd.LatestOrder = Ord.OrderDate
    AND LastOrd.CustomerID  = Ord.CustomerID

此处的假设是OrderDate字段可用于一个且仅一个订单 由客户(即客户没有具有相同OrderDate值的订单)。

答案 1 :(得分:0)

请这样使用。

SELECT  C.EmailAddress, k.OrderID, k.TaxAmount, k.OrderDate
FROM  Customers C
OUTER APPLY
(
    SELECT TOP 1 *
    FROM Orders O
    WHERE C.CustomerID = O.CustomerID
    AND O.TaxAmount > 100
    ORDER BY O.OrderDate DESC
)k

答案 2 :(得分:0)

最简单的方法我认为使用// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowFromAll", builder => builder .WithMethods("GET", "POST") .AllowAnyOrigin() .AllowAnyHeader()); }); ; services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCors("AllowFromAll"); app.UseMvc(); } } } 排名函数可以根据订单日期生成row_numbers,订单日期的销售税已经大于100。

ROW_NUMBER()

答案 3 :(得分:-1)

不确定预期的结果是什么,因为你没有发布,但我对你正在寻找的内容进行了有根据的猜测。

SELECT  C.EmailAddress, 
        C.OrderID, 
        C.TaxAmount, 
        C.OrderDate AS LatestOrder
FROM Customers AS C
INNER JOIN (
    Select CustomerID, 
           MAX(OrderDate) As OrderDate 
    FROM Customers 
    GROUP BY CustomerID
) CustomerMax
ON C.CustomerID=CustomerMax.CustomerID AND C.OrderDate=CustomerMax.OrderDate
WHERE C.TaxAmount > 100