有没有更好的方法来加入?

时间:2012-01-27 22:04:47

标签: sql sql-server sql-server-2005

我按季度列出了销售代理的销售情况:

Agent          Quarter Sales
----------------------------
Alex Andersen  2011Q1    358
Alex Andersen  2011Q2    289
Alex Andersen  2011Q3     27
Alex Andersen  2011Q4   2965
Brian Blogg    2010Q3    277
Brian Blogg    2010Q4    123
Brian Blogg    2011Q1    783
Brian Blogg    2011Q2      0
Christy Cliff  2011Q2    777
Christy Cliff  2011Q3    273
Christy Cliff  2011Q4    111
Christy Cliff  2012Q1    901

获得每个代理商最早季度和该季度销售额的最简单,最有效的查询是什么?

很容易找到“每个代理商的第一季度是什么?”:

SELECT agent, min(quarter) FROM salestable GROUP BY agent

但这不包括销售数字,所以我想我会加入:

SELECT agent, sales
FROM salestable s1
JOIN
(
   SELECT agent AS e, MIN(quarter) AS q
   FROM salestable
   GROUP by employee
) AS q1 ON q1.e=s1.agent AND q1.mq=s1.quarter

但这对我的数据集来说速度慢得令人无法接受。如果我可以使用游标,它只需要一次通过表,但使用查询似乎需要一个连接。是吗?

1 个答案:

答案 0 :(得分:6)

尝试这种变化,看看它是否更好:

WITH cteRowNum AS (
    SELECT agent, quarter, sales,
           ROW_NUMBER() OVER (PARTITION BY agent ORDER BY quarter) AS RowNum
        FROM salestable
)
SELECT agent, quarter, sales
    FROM cteRowNum
    WHERE RowNum = 1;