如何将此查询正确添加到查询设计器中的现有查询中?

How do I properly add this query into my existing query within Query Designer?

我目前在查询设计器中编写了以下查询。我昨天问了一个问题,它自己起作用了,但我想将它合并到我现有的报告中。

SELECT Distinct
       i.ProductNumber
  ,i.ProductType
  ,i.ProductPurchaseDate
  ,ih.SalesPersonComputerID
  ,ih.SalesPerson
  ,ic2.FlaggedComments

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 JOIN [SalesHistory] AS ih
    ON ih.SalesKey = i.SalesKey

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

我昨天的问题是,我想要一种方法来 select 仅针对每次销售发表的第一条评论。我查询 selecting 标记的评论,但我想要第一行和标记的评论。他们都将来自同一个 table。这是提供的查询,它可以独立运行,但我不知道如何让它与我现有的查询一起使用。

SELECT a.DateTimeCommented, a.ProductNumber, a.Comments, a.SalesKey 
FROM (
    SELECT 
            DateTimeCommented, ProductNumber, Comments, SalesKey,
            ROW_NUMBER() OVER(PARTITION BY ProductNumber ORDER BY DateTimeCommented) as RowN
    FROM [SalesComment]
    ) a 
WHERE a.RowN = 1

非常感谢您的帮助。

您可以结合使用行编号和聚合来获取 Flagged% 条评论和第一条评论。

您可能需要更改 PARTITION BY 子句以适应。

DISTINCT on the outer query is probably spurious, on the inner query it definitely is, as you have GROUP BY anyway. If you are getting multiple rows, don't just throw DISTINCT at it, instead think about your joins and whether you need aggregation.

The second LEFT JOIN logically becomes an INNER JOIN due to the WHERE predicate. Perhaps that predicate should have been in the ON instead?

SELECT
   i.ProductNumber
  ,i.ProductType
  ,i.ProductPurchaseDate
  ,ih.SalesPersonComputerID
  ,ih.SalesPerson
  ,ic2.FlaggedComments
  ,ic2.FirstComments

FROM [Products] i
        
LEFT OUTER JOIN 
    (SELECT
        MIN(CASE WHEN c2.RowN = 1 THEN c2.Comments) AS FirstComments
        ,c2.SalesKey 
        ,MIN(CASE WHEN c2.Comments like 'Flagged*%' THEN c2.Comments) AS FlaggedComments
        FROM (
            SELECT *,
              ROW_NUMBER() OVER (PARTITION BY ProductNumber ORDER BY DateTimeCommented) as RowN
            FROM [SalesComment]
        ) AS c2
        GROUP BY c2.SalesKey
    ) ic2 ON ic2.SalesKey = i.SalesKey

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

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