如何仅对具有特定列的记录分组

时间:2018-11-30 07:28:43

标签: sql-server

我有一个包含GROUP BY子句的查询。

我只想在FolioNumber上应用GROUP BY,因为由于UPDATE,同一记录的其他列中的数据正在快速变化。

这是示例查询,我希望您不需要示例数据,并且理解查询结构非常简单。

SELECT MAX(TransactionNo) [TransactionNo], [FolioNo], [SalesOrderDate], [Center], [Company], [Customer],
       [DeliveryAddress], [OfficialPhoneNo], [Item], [OrderQty], [UnitPrice], [Description], [FinishType], 
       [Remarks], [OrderNo], [BookNo], [CustomerAddress], [Customer], [DeliveryDate], [SalePerson]
       [Status], [Discount], [NetAmount], [GrossAmount], [InvoiceDiscount], [GSTTax], [DateFrom], [DateTo]

FROM tblPageIndex 
GROUP BY [FolioNo]

2 个答案:

答案 0 :(得分:2)

我认为您希望与每个FoliyoNo相关联的数据,其中TransactionNo最大。

您可以使用ROW_NUMBER()根据FoliyoNo对行进行分组,并为TransactionNo选择具有最大值的行

;WITH CTE AS (

SELECT [TransactionNo], [FolioNo], [SalesOrderDate], [Center], [Company], [Customer],
       [DeliveryAddress], [OfficialPhoneNo], [Item], [OrderQty], [UnitPrice], 
       [Description], [FinishType], [Remarks], [OrderNo], [BookNo], [CustomerAddress], 
       [Customer], [DeliveryDate], [SalePerson]
       [Status], [Discount], [NetAmount], [GrossAmount], [InvoiceDiscount], 
       [GSTTax], [DateFrom], [DateTo],
       ROW_NUMBER() OVER(PARTITION BY [FolioNo] ORDER BY TransactionNo DESC) AS RN

FROM tblPageIndex 

)

SELECT * FROM CTE WHERE RN = 1

从注释中可以看出,您希望每个TransactionNo中的所有行都具有最大FoliyoNo

因此您可以将ROW_NUMBER()更改为RANK()以获得所需的结果。

答案 1 :(得分:2)

您需要使用Over子句。在下面的示例查询中可能会为您提供帮助。由于您尚未提供任何用于单元测试的数据集。

SELECT MAX(TransactionNo) over (partition by FolioNo) as  [TransactionNo], [FolioNo], [SalesOrderDate], [Center], [Company], [Customer],
       [DeliveryAddress], [OfficialPhoneNo], [Item], [OrderQty], [UnitPrice], [Description], [FinishType], 
       [Remarks], [OrderNo], [BookNo], [CustomerAddress], [Customer], [DeliveryDate], [SalePerson]
       [Status], [Discount], [NetAmount], [GrossAmount], [InvoiceDiscount], [GSTTax], [DateFrom], [DateTo]

FROM tblPageIndex