SQL Server中前10条记录以及其他记录的剩余记录总数

时间:2019-05-27 07:52:57

标签: sql sql-server sql-server-2012

我有一个表,该表由4列组成-(id int,位置varchar(max),[date] datetime,Total_Sales Money),该表由输出中的20条记录组成,我想要11行,其中前10行是第11行应该是剩余行的总和,即Other_Location中的11到20。请帮助我获取查询。

我想要11行,其中前10行保持不变,第11行应该是剩余行的总和

3 个答案:

答案 0 :(得分:1)

您可以使用union选择前10行和1行总和

可能是代码:

SELECT id, location, date, total_sales FROM table limit 10 // where etc..
UNION
SELECT 0 as id, '' as location, 0 as date, sum(total_sales) as total_sales FROM table;

答案 1 :(得分:1)

在SQL Server 2012中,使用ROW_NUMBER()窗口函数,您可以实现此目的。创建ROW_NUMBER()来为每一行设置RowNum,并根据结果,使用UNION ALL将返回结果:

;WITH CTE AS (
    SELECT id, location, [date], Total_Sales,
           ROW_NUMBER() OVER (ORDER BY Id) AS RowNum
    FROM TableName
)

SELECT CAST(id AS VARCHAR(30)) AS Id,
       location, 
       CAST([date] AS VARCHAR(30)) AS [date], 
       CAST(Total_Sales AS VARCHAR(30)) AS Total_Sales 
FROM CTE 
WHERE RowNum BETWEEN 1 AND 10
UNION 
SELECT '11-20 ids' AS id, 
       '11-20 AS locations' as location, 
       '11-20 dates' AS [date], 
       SUM(Total_Sales) AS Total_Sales 
FROM CTE 
WHERE RowNum BETWEEN 11 AND 20

Demo on db<>fiddle

答案 2 :(得分:0)

我将使用9和条件聚合。这样,您可以使用一个row_number()来完成此操作:

group by