从一个具有相同ID的表中选择最小值和最大值(sql server)

时间:2017-03-10 04:00:21

标签: sql-server max min

我有这样的表:

| ID |        Date         |
|----|---------------------|
| 20 | 2017-03-01 08:00:00 |
| 20 | 2017-03-01 17:00:00 |
| 21 | 2017-03-01 07:00:00 |
| 21 | 2017-03-01 17:10:00 |

如何选择显示结果:

| ID |        Date         |        IN          |        OUT         |
|----|---------------------|--------------------|--------------------|
| 20 |      2017-03-01     |2017-03-01 08:00:00 |2017-03-01 17:00:00 |
| 21 |      2017-03-01     |2017-03-01 07:00:00 |2017-03-01 17:10:00 |

我无法找到查询,请帮助我,提前谢谢

5 个答案:

答案 0 :(得分:2)

您可以使用以下查询。

SELECT id, MIN(date), MAX(date) FROM yourTable GROUP BY id

答案 1 :(得分:1)

以下查询将返回,最短日期为IN时间,最长日期为每个ID的OUT时间。

SELECT  ID,CONVERT(DATE,([DATE]) ) AS [DATE],MIN([DATE]) AS [IN],MAX([DATE]) AS [OUT]
FROM    TABLE1
GROUP BY ID,CONVERT(DATE,([DATE]) )

注意: - 请不要将SQL KEYWORD用作列名(例如; - DATE,IN,OUT ...)

答案 2 :(得分:0)

尝试使用:汇总功能MIN,MAXGROUP BY将解决您的问题并为您提供预期结果,如下所示:

select id, cast(Edate as Date) EDate, min(Edate) inTime, max(Edate) outTime 
from myTable
group by id, cast(Edate as Date)

<强>输出

id  EDate       inTime                  outTime
20  2017-03-01  2017-03-01 08:00:00.000 2017-03-01 17:00:00.000
21  2017-03-01  2017-03-01 07:00:00.000 2017-03-01 17:10:00.000

答案 3 :(得分:0)

请尝试以下查询。

SELECT tf2.ID,tf2.Name AS ChildName,tf.Name AS Father,tf3.Name AS Mother 
FROM dbo.tbl_clildparent tc
INNER JOIN dbo.tbl_Family tf ON tc.Parent_id=tf.ID 
    AND tf.Gender='M'
INNER JOIN dbo.tbl_Family tf3 ON tc.Parent_id = tf3.ID 
    AND tf3.Gender='F'
LEFT OUTER JOIN dbo.tbl_Family tf2 ON tc.Child_id = tf2.ID

使用子查询

SELECT
  ID,
  to_char(DATE, 'yyyy-mm-dd'),
  MIN(DATE) AS IN,
  MAX(DATE) AS OUT
FROM Absensi_Log outer
GROUP BY ID,to_char(DATE, 'yyyy-mm-dd')

答案 4 :(得分:0)

CREATE TABLE #TEMP (Id INT,[Date] DATETIME)
INSERT INTO #Temp 
SELECT 20,'2017-03-01 08:00:00' UNION ALL
SELECT 20,'2017-03-01 17:00:00' UNION ALL
SELECT 21,'2017-03-01 07:00:00' UNION ALL
SELECT 21,'2017-03-01 17:10:00'

SELECT Id,CONVERT(DATE,[Date],103)[Date],Min([Date]) DateIN,Max([Date]) DateOUT FROM #Temp
GROUP BY Id,CONVERT(DATE,[Date],103)

DROP TABLE #Temp