编写 SQL 查询以仅返回使用 CTE 和内连接修改的最新记录

问题描述 投票:0回答:1

我相信我的 CTE 查询不正确。

WITH LastModified AS (
SELECT 
    Id, MAX(ModifiedON) as Last_Modified
FROM 
    EventTransaction
GROUP BY 
    ProductNumber)
SELECT 
   ProductNumber, ProductDescription, CreatedON, CreatedByUser as UserCreated, ModifiedON, ModifiedByUser as UserModified
FROM 
    EventTransaction
    INNER JOIN UserAccount on 
    EventTransaction.ModifiedByUser=UserAccount.UserAccountId
order by ProductNumber

不断收到错误消息 8120,级别 16,状态 1,第 48 行 列“EventTransaction.Id”在选择列表中无效,因为它未包含在聚合函数或 GROUP BY 子句中。

期望每个产品编号都有一行包含所选信息。 Select 语句和内连接工作。

sql mysqli common-table-expression
1个回答
0
投票

如果你想使用“WITH AS”结构,你应该创建如下内容:

WITH
TABLE1 AS (SELECT * FROM SOURCE)
, TABLE2 AS (SELECT * FROM SOURCE)
, TABLE3 AS (SELECT * FROM SOURCE)

SELECT
    a.*
    ,b.*
    ,c.*
FROM TABLE1 a 
LEFT JOIN TABLE2 b ON a.key = b.key
LEFT JOIN TABLE3 c ON a.key = c.key

这是您的查询的更正版本:

WITH LastModified AS (
    SELECT 
        ProductNumber, MAX(ModifiedON) as Last_Modified
    FROM 
        EventTransaction
    GROUP BY 
        ProductNumber
)

SELECT 
    ET.ProductNumber, 
    ET.ProductDescription, 
    ET.CreatedON, 
    ET.CreatedByUser as UserCreated, 
    ET.ModifiedON, 
    ET.ModifiedByUser as UserModified
FROM 
    EventTransaction ET
INNER JOIN 
    UserAccount UA on ET.ModifiedByUser = UA.UserAccountId
INNER JOIN 
    LastModified LM on ET.ProductNumber = LM.ProductNumber and ET.ModifiedON = LM.Last_Modified
ORDER BY 
    ET.ProductNumber;
© www.soinside.com 2019 - 2024. All rights reserved.