使用SQL Server

时间:2018-06-17 20:52:43

标签: sql sql-server

我正在尝试创建一个查询,它会将大于或等于$ 20.00的项目增加15%,但我似乎无法弄明白。这是我到目前为止所拥有的。一切都在工作,除了我不知道如何只为这些物品增加15%或20.00美元以上..

SELECT        Products.ProductID,
              Products.ProductName,
              CASE  
                WHEN (Products.CategoryID = 1) THEN 'Beverage'
                WHEN (Products.CategoryID = 2) THEN 'Sauce & Spread'
                WHEN (Products.CategoryID = 3) THEN 'Dessert'
                WHEN (Products.CategoryID = 4) THEN 'Cheese'
                WHEN (Products.CategoryID = 5) THEN 'Bread'
                WHEN (Products.CategoryID = 6) THEN 'Meat'
                WHEN (Products.CategoryID = 7) THEN 'Miscellaneous'
                WHEN (Products.CategoryID = 8) THEN 'Seafood'
                ELSE 'Unknown'
              END AS Categorys,
              Products.UnitPrice,
              FORMAT ((Products.UnitPrice * 1.15), 'N') AS NewPrice, 
              Suppliers.Name AS SupplierName
FROM          Products INNER JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID
ORDER BY ProductName

2 个答案:

答案 0 :(得分:2)

在查询中使用case语句可以解决问题。

SELECT    Products.ProductID,
          Products.ProductName,
          CASE  
            WHEN (Products.CategoryID = 1) THEN 'Beverage'
            WHEN (Products.CategoryID = 2) THEN 'Sauce & Spread'
            WHEN (Products.CategoryID = 3) THEN 'Dessert'
            WHEN (Products.CategoryID = 4) THEN 'Cheese'
            WHEN (Products.CategoryID = 5) THEN 'Bread'
            WHEN (Products.CategoryID = 6) THEN 'Meat'
            WHEN (Products.CategoryID = 7) THEN 'Miscellaneous'
            WHEN (Products.CategoryID = 8) THEN 'Seafood'
            ELSE 'Unknown'
          END AS Categorys,
          Products.UnitPrice,
          FORMAT (( CASE WHEN Products.UnitPrice > 20 THEN Products.UnitPrice * 1.15 ELSE Products.UnitPrice END), 'N') AS NewPrice, 
          Suppliers.Name AS SupplierName
FROM          Products INNER JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID
ORDER BY ProductName

答案 1 :(得分:1)

您可以使用CASEIIF

执行此操作
SELECT    Products.ProductID,
          Products.ProductName,
          Products.UnitPrice,
          ...
          AdjPrice = iif(Products.UnitPrice > 20, Products.unitPrice * 1.15, products.UnitPrice)

FROM          Products INNER JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID
ORDER BY ProductName