sql server加入同一个表

时间:2012-08-24 02:42:08

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

这是我在表格中的行:

Id    |       FromDate            |       ToDate             | prod_Id
------|---------------------------|--------------------------|-------
1     |   2012-08-13 07:00:00.000 |  2012-08-14 18:59:00.000 |    10
1     |   2012-08-13 07:00:00.000 |  2012-08-15 18:59:00.000 |    10
1     |   2012-08-13 07:00:00.000 |  2012-08-16 18:59:00.000 |    10 

我想得到如下结果:

Id  |   FromDate                  |        ToDate             | prod_Id
----|-----------------------------|---------------------------|---------
1   |    2012-08-13 07:00:00.000  |   2012-08-16 18:59:00.000 |   10 

怎么做?

3 个答案:

答案 0 :(得分:5)

 SELECT Id, MIN(FromDate), MAX(ToDate), prod_Id
 FROM TbName
 GROUP BY Id, prod_Id

答案 1 :(得分:2)

请试试这个sql。 我认为这就是你想要的。

SELECT Id, FromDate, MAX(ToDate), prod_Id
FROM TbName
GROUP BY Id, FromDate, prod_Id

答案 2 :(得分:1)

您可以采用以下方式

SELECT
p.dept,p.id,
u.FirstName +'+ ' '+ '+ u.LastName as CreatedBy,                            
v.FirstName +'+ ' '+ '+ v.LastName as ModifiedBy
from tblUserNew p
inner join tblUserNew u on p.CreatedBy=u.Id
inner join tblUserNew as v  on p.ModifiedBy=v.Id