列名称在CTE语句中不存在

时间:2018-11-26 17:22:47

标签: sql-server sql-server-2008

我正在尝试创建CTE语句:

WITH StartCash (StartCash) AS
(
    SELECT StartCash 
    FROM CashierInfo 
    WHERE CashierID = (SELECT MAX( CashierID) 
                       FROM CashierInfo  
                       WHERE UserID = 1 AND EndDate IS NULL)
)
SELECT
    StartCash, a.username AS Username, b.Adress AS Adress,
    (SUM(c.quantity * c.discountprice)) AS SumPrice,
    c.Printed AS Printed, c.CashierUserID AS CashierUserID,
    c.RetailDelivery AS RetailDelivery, c.TrnDocumentID 
FROM
    Users a 
JOIN
    InventoryTransTemp c ON c.CashierUserID = a.UserID 
JOIN
    DeliveryAdress b ON b.DeliveryAdressID = c.DeliveryAdressID 
WHERE
    c.cashieruserid =  1 
GROUP BY
    a.Username, b.Adress, c.Printed, 
    c.CashierUserID, c.RetailDelivery, c.TrnDocumentID

但是我遇到了错误

  

无效的列名“ StartCash”

2 个答案:

答案 0 :(得分:2)

StartCash不存在,因为您的CTE未包含在FROM子句中。

仅根据我在问题中看到的内容,我认为将CashierInfo.UserID联接到Users.UserID是安全的。 所以尝试这样的事情:

WITH StartCash
AS (
    SELECT StartCash
        ,UserID
    FROM CashierInfo
    WHERE CashierID = (
            SELECT MAX(CashierID)
            FROM CashierInfo
            WHERE UserID = 1
                AND EndDate IS NULL
            )
    )
SELECT sc.StartCash
    ,a.username AS Username
    ,b.Adress AS Adress
    ,(SUM(c.quantity * c.discountprice)) AS SumPrice
    ,c.Printed AS Printed
    ,c.CashierUserID AS CashierUserID
    ,c.RetailDelivery AS RetailDelivery
    ,c.TrnDocumentID
FROM StartCash sc
INNER JOIN Users a ON sc.UserID = a.UserID
INNER JOIN InventoryTransTemp c ON c.CashierUserID = a.UserID
INNER JOIN DeliveryAdress b ON b.DeliveryAdressID = c.DeliveryAdressID
WHERE c.cashieruserid = 1
GROUP BY sc.StartCash
    ,a.Username
    ,b.Adress
    ,c.Printed
    ,c.CashierUserID
    ,c.RetailDelivery
    ,c.TrnDocumentID

答案 1 :(得分:0)

您的from子句中没有CTE。您需要加入CTE,但您的CTE只有一个摘要值。 https://docs.microsoft.com/en-us/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-2017