按月和年分组以获得不同的月份和年份,然后组合为单个日期SQL

时间:2016-06-29 16:03:31

标签: sql-server

SELECT CONVERT(DATE,CAST([Year] AS VARCHAR(4))+'-'+
                    CAST([Month] AS VARCHAR(2))+'-'+
                    CAST('1' AS VARCHAR(2))) Date 
FROM (SELECT YEAR(Date) as [Year], MONTH(Date) as [Month] FROM [dbo].[Data] 
GROUP BY YEAR(Date), MONTH(Date)) x
                    ORDER BY Date DESC

使用单个查询是否有更好的方法来处理这个问题?

查询应该从表中返回唯一的月份和年份,但是作为组合日期。

3 个答案:

答案 0 :(得分:1)

IF OBJECT_ID ('tempdb..#TempT') IS NOT NULL DROP TABLE #TempT
CREATE TABLE #TempT(
    dt datetime)

INSERT INTO #TempT (dt) VALUES
('2016-10-11'),
('2016-10-3'),
('2016-9-13'),
('2016-9-16')

SELECT DISTINCT CAST(DATEADD(month, DATEDIFF(month, 0, dt), 0) as DATE) AS Dates
from #TempT

答案 1 :(得分:1)

样本数据对于这些类型的问题确实是必需的,但这个功能也可以为您提供帮助DATEFROMPARTS

SELECT 
  DATEFROMPARTS([Year], [Month], 01)
FROM 
(
  SELECT 
    YEAR(Date) as [Year], 
    MONTH(Date) as [Month] 
  FROM [dbo].[Data] 
  GROUP BY YEAR(Date), MONTH(Date)
) x
ORDER BY Date DESC

答案 2 :(得分:0)

此代码会记录您输入的任何日期,并将其评估为该月的第一天。有效地只查看月份和年份:

SELECT
    DATEADD(MM,DATEDIFF(MM,0, [Date] ),0) AS [YearMonth]
FROM [dbo].[Data]
ORDER BY
    DATEADD(MM,DATEDIFF(MM,0, [Date] ),0)
;