从组中的第一行中选择一些值,同时聚合其他值

时间:2018-01-18 21:56:31

标签: sql sql-server

我需要将一个表中的多个行组合到另一个表中的单个行中,为此,我们希望获得大多数列的最新数据,以及其他列的聚合数据。我们现在按照日期排序排名第一,但不幸的是,我们在某些字段上没有给出正确的值。如果可能的话,我想用一个声明来做这件事

当前SQL的示例(使用字符串插值)

INSERT INTO Invoices (InvoiceID, InvoiceNumber, InvoiceDate, Customer, State, Country, TaxRate, SaleDate, Freight, Subtotal, Tax, Total)
SELECT TOP 1 @InvoiceID, @InvoiceNumber, @InvoiceDate, Customer, State, Country, TaxRate, SaleDate, Freight, Subtotal, Tax, Total FROM Sales 
WHERE SaleNumber in ({SalesNumbers.ToString(",")}) ORDER BY SaleDate DESC

在示例中,我们希望最后三列(小计,税,​​总)是父表中所有匹配行的总和,但仍希望从最新数据中选择所有其他值(最近的销售)是否有一个在插入上执行此操作,或者我需要插入然后更新聚合后?

1 个答案:

答案 0 :(得分:0)

这是一种方法。由于您无法在没有分组的情况下混合聚合和非聚合,因此我将顶部1和聚合分成From子句中的子选择。

INSERT INTO Invoices (InvoiceID, InvoiceNumber, InvoiceDate, Customer, State, Country, TaxRate, SaleDate, Freight, Subtotal, Tax, Total) 
SELECT [InvoiceID],[InvoiceNumber],[InvoiceDate],[Customer],[State],[Country],[TaxRate],[SaleDate],[Freight]
  ,[Subtotal],[Tax],[Total]
  FROM 
  (SELECT top 1 [InvoiceID],[InvoiceNumber],[InvoiceDate],[Customer],[State],[Country],[TaxRate],[SaleDate],[Freight]
  FROM [Sales]
  where salesnumber in ({SalesNumbers.ToString(",")})
  order by saledate desc) recent_sale,
  (SELECT sum(Subtotal) Subtotal,sum([Tax]) Tax,sum([Total]) Total
  FROM [Sales]
  where salesnumber in ({SalesNumbers.ToString(",")}))  all_sales