如何使用SQL在一行中显示数据

时间:2018-02-05 15:00:52

标签: sql sql-server sql-server-2012

我在加入购物篮后订购了产品“Cookie”和“Coffee”。那么这是我的Order表:

This is my order table after I ordered 2 products:

然后我编写了如下代码:

SELECT Order.OrderDate
    , User.NAME
    , User.Surname
    , User.Phone
    , User.Adress
    , Product.ProductName
    , Order.Price
    , Order.Piece
    , Cargo.CargoPrice 
FROM Order 
INNER JOIN User ON Order.UserID = User.UserID 
INNER JOIN Product ON Order.ProductID = Product.ProductID 
INNER JOIN Cargo ON Order.CargoID = Cargo.CargoID 
WHERE Order.OrderDate = '2018-02-05 17:30:13.000' 
AND Order.UserID = '1'

所以输出如下:

This is my output after the SQL code:

因此,我的订单总价值必须为90 + 80 + 7 = 177,我想在一行中显示这些值:user nameuser surnametotal price,{{ 1}}。

1 个答案:

答案 0 :(得分:0)

我认为这适用于您的问题

SELECT 
      User.NAME
    , User.Surname
    , TotalPrice = SUM((Order.Price * Order.Piece) + MIN(Cargo.CargoPrice) )
    , Order.OrderDate
FROM Order 
INNER JOIN User ON Order.UserID = User.UserID 
INNER JOIN Product ON Order.ProductID = Product.ProductID 
INNER JOIN Cargo ON Order.CargoID = Cargo.CargoID 
WHERE Order.OrderDate = '2018-02-05 17:30:13.000' 
AND Order.UserID = '1'
GROUP BY
      User.NAME
    , User.Surname
    , Order.OrderDate