Sqlserver
 sql >> база данни >  >> RDS >> Sqlserver

t-sql select получава всички месеци в рамките на редица години

Господи хора... използването на "броящ рекурсивен CTE" или "rCTE" е също толкова лошо или по-лошо от използването на цикъл. Моля, вижте следващата статия защо казвам това.

http://www.sqlservercentral.com/articles/T-SQL/74118/

Ето един начин да го направите без RBAR, включително "скрития RBAR" на броещ rCTE.

--===== Declare and preset some obviously named variables
DECLARE @StartDate DATETIME,
        @EndDate   DATETIME
;
 SELECT @StartDate = '2010-01-14', --We'll get the month for both of these 
        @EndDate   = '2020-12-05'  --dates and everything in between
;
WITH
cteDates AS
(--==== Creates a "Tally Table" structure for months to add to start date
     -- calulated by the difference in months between the start and end date.
     -- Then adds those numbers to the start of the month of the start date.
 SELECT TOP (DATEDIFF(mm,@StartDate,@EndDate) + 1)
        MonthDate = DATEADD(mm,DATEDIFF(mm,0,@StartDate) 
                  + (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1),0)
   FROM sys.all_columns ac1
  CROSS JOIN sys.all_columns ac2
)
--===== Slice each "whole month" date into the desired display values.
 SELECT [Year]  = YEAR(MonthDate),
        [Month] = MONTH(MonthDate) 
   FROM cteDates
;


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Получаване на минимум две стойности в SQL

  2. R DBI ODBC грешка:nanodbc/nanodbc.cpp:3110:07009:[Microsoft][ODBC драйвер 13 за SQL Server]Невалиден индекс на дескриптор

  3. Настройка на SQL Server Reporting Services

  4. Осигурени данни в T-SQL

  5. Използвайте COLUMNPROPERTY() за връщане на информация за колона или параметър в SQL Server