1

我阅读了 berfore SQL Count for a Date ColumnSQL 以获取按日期计数,但这些并没有指出我的问题。

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

| 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 中可能吗?

谢谢

4

5 回答 5

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-数据

于 2012-05-07T12:18:51.703 回答
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
于 2012-05-07T12:19:15.497 回答
0
select VALUE, count(VALUE), datepart(d, MIN(TIME)) AS NEWTIME
from table1
group by datepart(d, TIME)

您可以使用其中之一MINMAX聚合函数。在您的情况下,这无关紧要,因为您通过datepart.

于 2012-05-07T12:14:31.550 回答
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 
于 2012-05-07T12:14:58.420 回答
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)

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

于 2012-05-07T12:20:14.077 回答