SQL使用if / else条件创建新列

时间:2015-12-21 15:46:53

标签: sql sql-server

我已经在这项任务上工作太久了,而且我仍然陷入困境。我需要做的是,在数据库AdventureWorks2014上工作,检索他们所做的客户ID和平均订单(当然是所有客户)。当我尝试插入另一个应该具有值的列(

)时,我的问题就开始了
  • ' Y'如果CustomerOrders> 10 * AverageOfOrders和
  • ' N'如果CustomerOrders< 10个* AverageOfOrders。

我应该使用CTE,但这并不重要。我用CASE语句做了,但我一直收到错误

  

关键字' CASE'附近的语法不正确。

如果有人能向我解释我做错了什么,那就太棒了。以下是我的代码:

WITH CustID AS
(
SELECT CustomerID, COUNT(CustomerID) AS "NrOfOrdersPerCustomer"
FROM Sales.SalesOrderHeader
GROUP BY CustomerID
),
AvgNr AS
(
SELECT AVG("NrOfOrdersPerCustomer") AS "AvgNrOfOrders"
FROM CustID
),
Joint AS
(
SELECT CustID.CustomerID, 'NULL' AS "Valuable", CustID."NrOfOrdersPerCustomer", AvgNr."AvgNrOfOrders", 10*AvgNr."AvgNrOfOrders" AS "MultipliedBy10"
    CASE 
    WHEN "NrOfOrdersPerCustomer" > "MultipliedBy10" THEN 'Y'
    ELSE 'N'
    FROM CustID, AvgNr
    END
)
SELECT * FROM Joint; 

3 个答案:

答案 0 :(得分:1)

最后一次CTE错误

    Joint AS
    (
    SELECT CustID.CustomerID, 
    'NULL' AS "Valuable", 
    CustID."NrOfOrdersPerCustomer", 
    AvgNr."AvgNrOfOrders", 
    10*AvgNr."AvgNrOfOrders" AS "MultipliedBy10" <-- missing , here
        CASE 
        WHEN "NrOfOrdersPerCustomer" > "MultipliedBy10" THEN 'Y'
        ELSE 'N' <-- END should come here
        FROM CustID, AvgNr
        END <-- not here
    )

您的上一次CTE应该是

    Joint AS
    (
    SELECT CustID.CustomerID, 
    NULL AS "Valuable", 
    CustID."NrOfOrdersPerCustomer", 
    AvgNr."AvgNrOfOrders", 
    10*AvgNr."AvgNrOfOrders" AS "MultipliedBy10",
        CASE 
        WHEN "NrOfOrdersPerCustomer" > "MultipliedBy10" THEN 'Y'
        ELSE 'N' END AS Computed_Column
        FROM CustID, AvgNr
    )

答案 1 :(得分:1)

已经有一个答案可以解释你的语法错误(缺少逗号和不正确的案例表达),但是,我想我会发布一个更简单的替代解决方案:

WITH CustID AS
(
    SELECT CustomerID, COUNT(CustomerID) AS NrOfOrdersPerCustomer
    FROM Sales.SalesOrderHeader
    GROUP BY CustomerID
)
SELECT  CustomerID,
        NrOfOrdersPerCustomer,
        AVG(NrOfOrdersPerCustomer) OVER() AS AvgNrOfOrders,
        AVG(NrOfOrdersPerCustomer) OVER() * 10 AS MultipliedBy10,
        CASE WHEN NrOfOrdersPerCustomer >  AVG(NrOfOrdersPerCustomer) OVER() * 10 THEN 'Y'
            ELSE 'N' 
        END AS Valuable
FROM    CustID;

这利用了一个窗口函数 - AVG(NrOfOrdersPerCustomer) OVER() - 意味着你可以获得所有客户的平均值而无需单独的子查询。我也从你的别名中删除了引号,除非你的别名包含特殊字符,否则没有其他理由说它们是没有必要的,我发现它们非常分散注意力,特别是在不经常使用时。

答案 2 :(得分:0)

SELECT之后AS "MultipliedBy10"行的末尾,您需要一个逗号。此外,您的CASE声明最终会失灵。 END需要在FROM语句之前。更正如下:

WITH CustID AS
(
SELECT CustomerID, COUNT(CustomerID) AS "NrOfOrdersPerCustomer"
FROM Sales.SalesOrderHeader
GROUP BY CustomerID
),
AvgNr AS
(
SELECT AVG("NrOfOrdersPerCustomer") AS "AvgNrOfOrders"
FROM CustID
),
Joint AS
(
SELECT CustID.CustomerID, 'NULL' AS "Valuable", CustID."NrOfOrdersPerCustomer", AvgNr."AvgNrOfOrders", 10*AvgNr."AvgNrOfOrders" AS "MultipliedBy10",
    CASE 
    WHEN "NrOfOrdersPerCustomer" > "MultipliedBy10" THEN 'Y'
    ELSE 'N'
    END
    FROM CustID, AvgNr

)
SELECT * FROM Joint;