每天选择最小(价值)表格

时间:2011-05-09 10:37:22

标签: sql datetime min

我有下表

date_time,data_value

date_time               data_value
----------------------- ----------------------
2011-03-28 15:05:29.000 20  
2011-03-28 15:55:39.000 40  
2011-03-28 16:25:45.000 30

2011-03-28 23:37:11.000 10  
2011-03-29 04:43:12.000 44  
2011-03-29 05:13:18.000 55  
2011-03-29 05:28:21.000 52  
2011-03-29 05:48:25.000 23  
2011-03-29 06:13:30.000 8  
2011-03-29 07:03:40.000 34  
2011-03-29 08:34:01.000 25  
2011-03-29 09:34:20.000 35  
2011-03-29 09:49:23.000 23  
2011-03-30 16:00:55.000 20

我想获得sql中每个日期的最小值:

2011-03-29 06:13:30.000 8  
2011-03-28 15:05:29.000 20

有什么建议吗?

7 个答案:

答案 0 :(得分:2)

在SQL Server 2005 +中:

WITH ranked AS (
  SELECT
    date_time,
    data_value,
    rownum = ROW_NUMBER() OVER (
      PARTITION BY DATEADD(day, DATEDIFF(day, 0, date_time), 0)
      ORDER BY data_value
    )
  FROM atable
)
SELECT
  date_time,
  data_value
FROM ranked
WHERE rownum = 1

答案 1 :(得分:0)

试试那些:

SELECT FROM_DAYS(TO_DAYS(data_time)) AS dt, min(data_value) FROM table GROUP BY TO_DAYS(NOW())

SELECT DATE_FORMAT(data_time,'YYY-MM-01') AS dt, min(data_value) FROM table GROUP BY dt

答案 2 :(得分:0)

这有用吗?

SELECT date_time, MIN(data_value)
FROM TABLE
GROUP BY date_time

对不起,现在你已经格式化了显然不起作用的数据!你需要将一个函数应用于date_time,只删除日期并忽略时间部分。

在MySQL(以及其他例如DB2)中,您可以这样做:

   SELECT DATE(date_time), MIN(data_value)
    FROM TABLE
    GROUP BY DATE(date_time)

对于SQL Server,这看起来应该可行,请有人验证:

SELECT CONVERT(varchar(10), date_time), MIN(data_value)
FROM TABLE
GROUP BY CONVERT(varchar(10), date_time)

答案 3 :(得分:0)

这样的东西
  select TO_DAYS(date_time) as dt,  min(date_time) from xxx group by dt;

答案 4 :(得分:0)

select d(date_time), min(data_value)
from table
group by d(date_time)

其中d是从date_time中提取日期部分的函数。 (查看SQL参考手册中的函数名称)。

在Oracle SQL中,该函数为trunc

答案 5 :(得分:0)

试试这个

select min(val),substring(date,1,10) from table group by substring(date,1,10)

答案 6 :(得分:0)

 SELECT (ord_date), min([qty])

      FROM [pubs].[dbo].[sales]

     group by [ord_date]

     order by ord_date