SQL Server:显示分组记录的第一行

时间:2009-04-09 22:47:49

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

我试图编写一个查询,输出类似于下面最后一批记录的内容。当然,它可以在Reporting Services和Crystal Reports中使用,但只是将其丢弃,以查看是否可以在SSMS / QA中使用:

Table:
id name amount
-- ---- ------
 1 rob   23.00
 2 rob   34.00
 3 dan   45.00
 4 dan   56.00

select name, amount from t1 
Query resulting in:
name amount
---- ------
rob   23.00
rob   34.00
dan   45.00
dan   56.00

DESIRED result:
name amount
---- ------
rob   23.00
      34.00
dan   45.00
      56.00

谢谢!

1 个答案:

答案 0 :(得分:3)

试试这个:

SELECT CASE WHEN _rank = 1 THEN name ELSE '' END AS name, amount
FROM (
    SELECT name, amount,
        ROW_NUMBER() OVER (PARTITION BY name ORDER BY amount ASC) AS _rank
    FROM t1
) q