如何从sql中的表中的列获取最新日期?

时间:2016-08-05 04:04:06

标签: mysql sql asp.net sql-server

我正在尝试使用sql,asp.net从我的OrderItem表中获取最新日期。但是,当我运行程序时,它们会显示以下错误: Incorrect syntax near the keyword 'from'.

以下是我的代码:

    string strconnect =  ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
    SqlConnection myConnect = new SqlConnection(strconnect);

    string command = "
      Select OrderItem.ProductID, Product.Name, OrderItem.TotalQty, Product.UnitPrice, OrderItem.TotalPrice 
      FROM OrderItem 
      INNER JOIN Product ON OrderItem.ProductID=Product.ProductID 
      WHERE OrderDate = MAX(OrderDate) from OrderItem";
    SqlCommand cmd = new SqlCommand(command, myConnect);

    myConnect.Open();

    SqlDataReader reader = cmd.ExecuteReader();

    GridView1.DataSource = reader;
    GridView1.DataBind();
    reader.Close();
    myConnect.Close();

请指教!

4 个答案:

答案 0 :(得分:0)

您需要从OrderItem"中删除"在您的WHERE条件中,因为您已在FROM子句中指定。

SELECT
    i.ProductID,
    p.Name,
    i.TotalQty,
    p.UnitPrice,
    i.TotalPrice 
FROM 
    OrderItem i
        INNER JOIN Product p
            ON i.ProductID = p.ProductID 
WHERE
    i.OrderDate = (SELECT MAX(OrderDate) 
                   FROM OrderItem 
                   WHERE OrderItem.ProductID = i.ProductID)

答案 1 :(得分:0)

SELECT o.ProductID, p.Name, o.TotalQty, p.UnitPrice, o.TotalPrice 
FROM OrderItem AS o
INNER JOIN Product AS p ON o.ProductID = p.ProductID
ORDER BY o.OrderDate DESC
LIMIT 1

啊,你正在使用SQL-server,试试这个:(但是没有经过测试)

SELECT TOP 1 o.ProductID, p.Name, o.TotalQty, p.UnitPrice, o.TotalPrice 
FROM OrderItem AS o
INNER JOIN Product AS p ON o.ProductID = p.ProductID
ORDER BY o.OrderDate DESC

答案 2 :(得分:0)

这取决于订单日期的数据类型。您可能需要更改变量的数据类型或应用截断。

declare @MaxOrderDate datetime
select @MaxOrderDate = MAX(OrderItem.OrderDate) from OrderItem

Select
    OrderItem.ProductID,
    Product.Name,
    OrderItem.TotalQty,
    Product.UnitPrice,
    OrderItem.TotalPrice 
FROM 
    OrderItem 
        INNER JOIN Product 
            ON OrderItem.ProductID=Product.ProductID 
WHERE
    OrderItem.OrderDate = @MaxOrderDate

答案 3 :(得分:0)

您应该更改WHERE子句中的子查询。

SELECT OrderItem.ProductID, Product.Name, OrderItem.TotalQty, Product.UnitPrice, OrderItem.TotalPrice 
FROM OrderItem 
INNER JOIN Product ON OrderItem.ProductID=Product.ProductID 
WHERE OrderDate = ( SELECT MAX(OrderDate) FROM OrderItem );