选择所有行并忽略第一行

时间:2016-05-01 22:46:22

标签: sql sql-server sql-server-2008 tsql

我目前正在使用以下返回25行的SQL查询。如何修改它以忽略第一行:

SELECT fiscal_year, SUM(total_sales) as sum_of_year, AVG(SUM(total_sales)) 
OVER () as avg_sum 
FROM sales_report 
GROUP BY fiscal_year 
ORDER BY fiscal_year ASC

我正在使用SQL Server 2008。

感谢。

5 个答案:

答案 0 :(得分:3)

您可以在SQL Server 2008中使用EXCEPT

SELECT fiscal_year, SUM(total_sales) as sum_of_year, AVG(SUM(total_sales)) 
OVER () as avg_sum 
FROM sales_report 
GROUP BY fiscal_year

EXCEPT

SELECT TOP 1 fiscal_year, SUM(total_sales) as sum_of_year, AVG(SUM(total_sales)) 
OVER () as avg_sum 
FROM sales_report 
GROUP BY fiscal_year 
ORDER BY fiscal_year ASC

对于SQL Server 2012及更高版本,您可以使用FETCH OFFSET

答案 1 :(得分:0)

假设这正是您查询它的方式,那么: SELECT fiscal_year, SUM(total_sales) as sum_of_year, AVG(SUM(total_sales)) OVER () as avg_sum FROM sales_report WHERE fiscal year <> (SELECT MIN(Fiscal_year) FROM sales_report)) GROUP BY fiscal_year ORDER BY fiscal_year ASC

然后你可以删除“order by” 适用于所有版本

答案 2 :(得分:0)

您可以使用ROW_NUMBER窗口功能

;with cte as
(
SELECT Row_number()over(order by fiscal_year) as RN,fiscal_year, SUM(total_sales) as sum_of_year, AVG(SUM(total_sales)) 
OVER () as avg_sum 
FROM sales_report 
GROUP BY fiscal_year 
)
select * 
From cte
Where RN <> 1
ORDER BY fiscal_year ASC

答案 3 :(得分:0)

希望这是正确的。这就是我试图做到的:

SELECT fiscal_year
    ,a.sum_of_year
    ,AVG(SUM(a.sum_of_year)) OVER () AS avg_sum
FROM (
    SELECT Row_number() OVER (
            ORDER BY fiscal_year
            ) AS RN
        ,fiscal_year
        ,SUM(total_sales) AS sum_of_year
    FROM test_fiscal
    GROUP BY fiscal_year
    ) a
WHERE a.rN > 1
GROUP BY fiscal_year
    ,rn
    ,a.sum_of_year
ORDER BY fiscal_year ASC

答案 4 :(得分:0)

使用下面的查询来构建完美的查询

WITH cte_customers AS (
    SELECT 
        ROW_NUMBER() OVER(
             ORDER BY 
                first_name, 
                last_name
        ) row_num, 
        customer_id, 
        first_name, 
        last_name
     FROM 
        sales.customers
) SELECT 
    customer_id, 
    first_name, 
    last_name
FROM 
    cte_customers
WHERE 
    row_num <> 1;