日期:2014-05-17  浏览次数:20500 次

Sql的一个常见问题l
Card ADate ATime  
002001 2012-09-02 13:03:00  
002001 2012-09-02 14:23:00
769041 2012-09-02 13:16:00
769101 2012-09-02 14:23:00  
------------------------------------------------
要的结果是
Card ADate ATime Mark
002001 2012-09-02 13:03:00 进  
002001 2012-09-02 14:23:00 出
769041 2012-09-02 13:16:00 进
769101 2012-09-02 14:23:00 进
-------------------------------------------
就是在原始数据上加一列,当002001只有一行的话显示为进,有第二行的话显示为出,这个SQL语句怎么写?

------解决方案--------------------
SQL code
--> 测试数据:[tb]
IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb]
GO
CREATE TABLE [tb]([Card] VARCHAR(6),[ADate] DATETIME,[ATime] time)
INSERT [tb]
SELECT '002001','2012-09-02','13:03:00' UNION ALL
SELECT '002001','2012-09-02','14:23:00' UNION ALL
SELECT '769041','2012-09-02','13:16:00' UNION ALL
SELECT '769101','2012-09-02','14:23:00'
GO

--> 开始查询:
select [Card],
       [ADate],
       [ATime],
       case when rn=1 then'进' else '出' end as Mark
from 
(SELECT *,rn=row_number() over(partition by [Card] order by [ADate],[ATime]) FROM [tb])a
-------------------------------------------
-->结果集
/*
Card   ADate                   ATime            Mark
-----------------------------------------------------
002001 2012-09-02 00:00:00.000 13:03:00          进
002001 2012-09-02 00:00:00.000 14:23:00          出
769041 2012-09-02 00:00:00.000 13:16:00          进
769101 2012-09-02 00:00:00.000 14:23:00          进
*/

------解决方案--------------------
LS就是MSSQL的
------解决方案--------------------
探讨

Ls二位都是ORACLE的方式呀?有没SQL SERVER的?求解!