从每个组的第一行和最后一行获取数据

时间:2014-09-16 13:27:44

标签: sql sql-server group-by

我发现了很多类似的话题,但我无法理解这些话题,无法解决我的具体案例。

A有一个包含以下基本结构的表:

+------------------------+
| id | session ID | bal  |
+------------------------+
| 0  | 00000002 | 100    |
| 1  | 00000002 | 120    |
| 2  | 00000002 | 140    |
| 3  | 00000001 | 900    |
| 4  | 00000001 | 800    |
| 5  | 00000001 | 500    |
+------------------------+ 

我需要创建一个(Microsoft SQL)查询,该查询根据顺序值返回每个唯一的sessionID以及第一个(" start")和last(" end")bal条目ID列的。结果如下:

+---------------------------+
| session ID | start | end  |
+---------------------------+
| 00000002   | 100   | 140  |
| 00000001   | 900   | 500  |
+---------------------------+

我怎样才能做到这一点?

5 个答案:

答案 0 :(得分:7)

编辑在回复您的评论时,SQL Server支持窗口功能。查找每bal的第一个和最后Session ID个值的一种方法是:

select  distinct [Session ID]
,       first_value(bal) over (partition by [Session ID] order by id) as [start]
,       first_value(bal) over (partition by [Session ID] order by id desc) as [end]
from    Table1

Example at SQL Fiddle.

另一种方式(有许多方法)是增加和减少行数:

select  [Session ID]
,       max(case when rn1 = 1 then bal end) as [start]
,       max(case when rn2 = 1 then bal end) as [end]
from    (
        select  row_number() over (partition by [Session ID] order by id) as rn1
        ,       row_number() over (partition by [Session ID] order by id desc) as rn2
        ,       *
        from    Table1
        ) as SubQueryAlias
group by
        [Session ID]

Example at SQL Fiddle.

答案 1 :(得分:3)

您可以使用JOINCommon Table Expression来提高可读性:

with CTE as
(
    select 
        sessionId, min(id) as firstId, max(id) as lastId
    from 
        log
    group by sessionId
)
select
    CTE.sessionId, Log1.bal as start, Log2.bal as [end]
from
    CTE
    join Log as Log1 on Log1.id = CTE.firstId
    join Log as Log2 on Log2.id = CTE.lastId

请参阅SQL Fiddle

答案 2 :(得分:2)

我认为bal是数字(虽然它不必在这种情况下,因为所有条目的长度都是3)

select sessionID
     , min(bal) as start
     , max(bal) as end
from table_name
group by sessionID

其中" table_name"是你的表的名称

答案 3 :(得分:0)

在MySQL中可能是这样的:

SELECT `session ID`, MIN(bal) AS start, MAX(bal) AS end FROM `yourtable` WHERE `session ID` IN (
    SELECT DISTINCT(`session ID`) FROM `yourtable`
);

答案 4 :(得分:-1)

  

SELECT FIRST(column_name),LAST(column_name)FROM table_name;   http://forums.mysql.com/read.php?65,363723,363723