分组 UNION ALL

Nel*_*son 0 sql-server union

无论我如何尝试对该查询生成的记录集进行分组,它都不会这样做。查询工作正常,问题是尝试按 A 分组

SELECT     CountryCode + + ProductNumber + + StockType AS A, 
           Quantity AS B, 
           Description AS C, 
           Price AS D

FROM       dbo.vwSalesInvoiceWHandling
UNION ALL
SELECT     CountryCode + + ProductNumber + + StockType AS A,  
           Quantity AS B, 
           Description AS C, 
           Price AS D

FROM       dbo.vwSalesInvoiceWOHandling
Run Code Online (Sandbox Code Playgroud)

ype*_*eᵀᴹ 5

您需要使用派生表或 CTE。使用派生表:

SELECT 
    A,
    SUM(B) AS SumQuantity,
    MIN(D) AS MinPrice             -- etc
FROM
  ( SELECT     CountryCode + ProductNumber + StockType AS A, 
               Quantity AS B, 
               Description AS C, 
               Price AS D

    FROM       dbo.vwSalesInvoiceWHandling
    UNION ALL
    SELECT     CountryCode + ProductNumber + StockType AS A,  
               Quantity AS B, 
               Description AS C, 
               Price AS D

    FROM       dbo.vwSalesInvoiceWOHandling
  ) 
    AS x      -- alias for the derived table
GROUP BY
    A ;
Run Code Online (Sandbox Code Playgroud)

或者,在两个表中进行分组,然后合并所有。在这种情况下,您将需要在派生表中进行另一个分组,但它可能会更有效,主要是因为您可以按计算列更改分组(CountryCode + ProductNumber + StockType)变为GROUP BY CountryCode, ProductNumber, StockType

SELECT 
    CountryCode + ProductNumber + StockType AS A,
    SUM(B) AS SumQuantity,
    MIN(D) AS MinPrice             -- etc
FROM
  ( SELECT     CountryCode, ProductNumber, StockType, 
               SUM(Quantity) AS B, 
               MIN(Price) AS D

    FROM       dbo.vwSalesInvoiceWHandling
    GROUP BY   CountryCode, ProductNumber, StockType
    UNION ALL
    SELECT     CountryCode, ProductNumber, StockType,  
               SUM(Quantity) AS B, 
               MIN(Price) AS D

    FROM       dbo.vwSalesInvoiceWOHandling
    GROUP BY   CountryCode, ProductNumber, StockType
  ) 
    AS x      -- alias for the derived table
GROUP BY
    CountryCode, ProductNumber, StockType ;
Run Code Online (Sandbox Code Playgroud)