操作系统 - WindowsXP
SQL Server Management Studio 2008 R2
我试图根据发布日期计算项目数量,而不是日期和时间。但是,某些项目具有相同的发布日期,但具有不同的时间,并被视为单独的项目。只要项目具有相同的日期,我希望它被计算在内。
服务器上的“释放”是“日期时间”
Select ProjectName, count(ProjectName) as Count, (Releasedate)
From DBTable Where Releasedate >= convert(nvarchar,(getdate()))
Group by projectname,releasedt
当前结果:
ProjectName Count Releasedate
Project_Nm_1 1 2010-03-27 00:00:00
Project_Nm_1 1 2010-03-27 08:00:00
Project_Nm_2 1 2010-03-27 00:00:00
Project_Nm_2 1 2010-03-27 08:00:00
我想看看:
Project_Nm_1 2 2010-03-27
Project_Nm_2 2 2010-03-27
答案 0 :(得分:3)
SQL Server 2008引入了新的 DATE
数据类型,它正是您正在寻找的 - 只处理日期,没有任何时间。所以只需CAST
你的字段到DATE
,你就可以了:
SELECT
ProjectName, COUNT(ProjectName) as Count, CAST(Releasedate AS DATE)
FROM
dbo.DBTable
WHERE
CAST(Releasedate AS DATE) >= CAST(GETDATE() AS DATE)
GROUP BY
projectname, CAST(ReleaseDate as DATE)
答案 1 :(得分:1)
要仅按日期分组,请尝试使用CONVERT功能:
GROUP BY projectname, CONVERT(nvarchar, Releasedate, 101)
您需要在选择列列表中使用相同的CONVERT
函数调用,以便查询的输出也只显示日期。
答案 2 :(得分:0)
Select
ProjectName, count(ProjectName) as CountProjects, Releasedate
From
DBTable
Where
Releasedate >= convert(nvarchar, getdate())
Group by
projectname,releasedt
Order by
CountProjects desc
P.S。选择任何列的别名时不要使用内置函数
答案 3 :(得分:0)
您可以使用GROUP BY
DATEPART
所需日期的各个部分
SELECT
ProjectName,
Count(*),
DATEPART(year, Releasedate) as ReleaseYear,
DATEPART(month, Releasedate) as ReleaseMonth,
DATEPART(day, Releasedate) as ReleaseDay
FROM
DBTable
WHERE
Releasedate >= convert(nvarchar,(getdate()))
GROUP BY
ProjectName,
DATEPART(year, Releasedate),
DATEPART(month, Releasedate),
DATEPART(day, Releasedate)
如果您愿意,我会将这些部分合并为一个字段作为练习,但这会忽略分组时Releasedate
的时间部分
答案 4 :(得分:0)
您可以使用
获取ReleaseDate日期时间的日期部分DateAdd(dd, 0, DateDiff(dd, 0, ReleaseDate))
因此您的查询变为
SELECT
ProjectName,
Count(ProjectName) as Count,
DateAdd(dd, 0, DateDiff(dd, 0, ReleaseDate)) as ReleaseDate
FROM
DBTable
WHERE
ReleaseDate >= getdate()
GROUP BY
ProjectName,
DateAdd(dd, 0, DateDiff(dd, 0, ReleaseDate))
如果您发现自己经常从日期时间剥离时间,则将其封装在UDF中。
答案 5 :(得分:0)
解释:
declare @dt datetime
set @dt = '2010/12/22 12:34:56'
print @dt
print convert(char(8), @dt, 112)
结果:
Dec 22 2010 12:34PM
20101222
所以,使用
GROUP BY convert(char(8), releasedt, 112)