我有一个包含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]
答案 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