Sql COUNT列按日期并选择对应日期

时间:2012-05-07 12:08:45

标签: sql sql-server-2005

我读过ber SQL Count for a Date ColumnSQL to get count by date,但这些并没有指出我的问题。

我有以下表记录(该表只有两列)

| VALUE   | TIME               |
--------------------------------
| test    | 04.05.2012 11:46:46|
| test2   | 04.05.2012 11:46:49|
| test3   | 06.05.2012 11:47:46|
| test2   | 05.05.2012 11:47:46|
| test    | 04.05.2012 11:51:46|

我希望显示如下:

| VALUE   | COUNT   | NEWTIME  |
--------------------------------
| test    | 2       |04.05.2012|
| test2   | 1       |04.05.2012|
| test2   | 1       |05.05.2012|
| test3   | 1       |06.05.2012|

我使用VALUE作为day的日期部分计算TIME,如:

select datepart(d, TIME), count(VALUE) from table1
group by datepart(d, TIME)

如何获取其他NEWTIME列?它可以在SQL Server 2005中使用吗?

谢谢

5 个答案:

答案 0 :(得分:2)

select VALUE,
       count(*) as COUNT,
       dateadd(day, datediff(day, 0, TIME), 0) as NEWTIME
from YourTable
group by VALUE, dateadd(day, datediff(day, 0, TIME), 0)

SE-Data

答案 1 :(得分:1)

您可以添加它并将其格式化,但您还必须按照它进行分组。

select value, datepart(d, TIME), count(VALUE), datepart(mmonth, time) + '.' + datepart(day, time) + '.' + datepart(year, time) as newtime
from table1
group by datepart(d, TIME, newtime) 

如果您不关心将句号用作分隔符,那么可以更容易一些。

select value, datepart(d, TIME), count(VALUE), convert(varchar, time, 101) as newtime
from table1
group by datepart(d, TIME, newtime) 

我也注意到你的输出中有重复,个人而言,我会这样做:

select value, count(*) as cnt, convert(varchar, time, 101) as newtime
from table1
group by value, newtime

答案 2 :(得分:0)

select VALUE, count(VALUE), datepart(d, MIN(TIME)) AS NEWTIME
from table1
group by datepart(d, TIME)

您可以使用MINMAX聚合函数。在您的情况下,当您通过datepart整天级别进行分组时,无关紧要。

答案 3 :(得分:0)

没有测试,但我会这样做

select VALUE, count(*) AS COUNT, convert(date, max(TIME)) AS NEWTIME --max , min whatever 
from table1
group by VALUE, datepart(d, TIME) --dont know why you group by timne not value 

答案 4 :(得分:0)

我真的不明白你的问题,但如果我理解它是正确的,你想在时间栏的短日期对数据进行分组?如果是这样,结果是:

select max(VALUE) as VALUE, count(VALUE) as count, CONVERT(VARCHAR(10), TIME , 104) as newtime
from table1
group by CONVERT(VARCHAR(10), TIME , 104)

如果你不按他们分组,我不明白为什么要显示这些值