You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Query Designer的现有查询中加入获取销售首条评论的查询

合并查询实现方案

你可以将获取首条评论的逻辑封装为独立子查询,通过左连接关联到原有查询中,两类评论的提取逻辑互不影响,修改后的完整SQL如下:

SELECT DISTINCT
       i.ProductNumber
      ,i.ProductType
      ,i.ProductPurchaseDate
      ,ih.SalesPersonComputerID
      ,ih.SalesPerson
      ,ic2.FlaggedComments
      ,first_c.FirstCommentDateTime -- 首条评论时间
      ,first_c.FirstComment -- 首条评论内容
FROM [Products] i
        
LEFT OUTER JOIN 
    (SELECT DISTINCT
        MIN(c2.Comments) AS FlaggedComments
        ,c2.SalesKey 
        FROM [SalesComment] AS c2
        WHERE c2.Comments LIKE 'Flagged*%'
        GROUP BY c2.SalesKey) ic2 
    ON ic2.SalesKey = i.SalesKey

-- 新增首条评论关联
LEFT OUTER JOIN
    (SELECT 
            DateTimeCommented AS FirstCommentDateTime,
            Comments AS FirstComment,
            ProductNumber
     FROM (
            SELECT 
                    DateTimeCommented, Comments, ProductNumber,
                    ROW_NUMBER() OVER(PARTITION BY ProductNumber ORDER BY DateTimeCommented ASC) as RowN
            FROM [SalesComment]
          ) a 
     WHERE a.RowN = 1
    ) first_c
    ON first_c.ProductNumber = i.ProductNumber

LEFT JOIN [SalesHistory] AS ih
    ON ih.SalesKey = i.SalesKey

WHERE
  i.SaleDate BETWEEN @StartDate AND @StopDate
AND ih.Status = 'SOLD'

说明

  • 新增的first_c子查询完全复用了你之前获得的首条评论提取逻辑,按产品分组取最早的第一条评论
  • 用LEFT JOIN关联可保证没有评论的产品数据不会被过滤,和原有查询逻辑一致
  • 如果业务上首条评论需要按销售单(SalesKey)维度而非产品维度提取,只需要把first_c子查询中的PARTITION BY ProductNumber改为PARTITION BY SalesKey,关联条件也对应改为ON first_c.SalesKey = i.SalesKey即可
  • 可选优化:你现有查询将ih.Status = 'SOLD'写在WHERE子句中,会让针对SalesHistory的LEFT JOIN实际等效于INNER JOIN,如果你业务上确实只需要保留已售出的产品数据可以保留该写法,否则建议将该条件移动到LEFT JOIN SalesHistory的ON子句中。

内容的提问来源于stack exchange,提问作者user17482884

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 05:54:00