Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

menampilkan minggu pelaporan

Menggunakan DATEADD dan memperbarui inisialisasi @interval dan logika loop yang diperbarui:

DECLARE @REPORT_DATE DATETIME, @WEEK_BEGINING VARCHAR(10)
SELECT @REPORT_DATE = '2011-01-01T00:00:00'
--SELECT @REPORT_DATE = GETDATE() -- should grab the date now.
SELECT @WEEK_BEGINING = 'MONDAY'
IF @WEEK_BEGINING = 'MONDAY'
SET DATEFIRST 1
ELSE IF @WEEK_BEGINING = 'TUESDAY'
SET DATEFIRST 2
ELSE IF @WEEK_BEGINING = 'WEDNESDAY'
SET DATEFIRST 3
ELSE IF @WEEK_BEGINING = 'THURSDAY'
SET DATEFIRST 4
ELSE IF @WEEK_BEGINING = 'FRIDAY'
SET DATEFIRST 5
ELSE IF @WEEK_BEGINING = 'SATURDAY'
SET DATEFIRST 6
ELSE IF @WEEK_BEGINING = 'SUNDAY'
SET DATEFIRST 7
DECLARE @WEEK_START_DATE DATETIME, @WEEK_END_DATE DATETIME
--GET THE WEEK START DATE
SELECT @WEEK_START_DATE = @REPORT_DATE - (DATEPART(DW, @REPORT_DATE) - 1)
--GET THE WEEK END DATE
SELECT @WEEK_END_DATE = @REPORT_DATE + (7 - DATEPART(DW, @REPORT_DATE))
PRINT 'Week Start: ' + CONVERT(VARCHAR, @WEEK_START_DATE)
PRINT 'Week End: ' + CONVERT(VARCHAR, @WEEK_END_DATE)

DECLARE @Interval int = datediff(WEEK,getdate(),@WEEK_START_DATE)+1

SELECT [email protected]_START_DATE
, [email protected]_END_DATE
INTO #WeekList

WHILE @Interval <= 0
    BEGIN
    set @WEEK_START_DATE=DATEADD(WEEK,1,@WEEK_START_DATE)
    set @WEEK_END_DATE=DATEADD(WEEK,1,@WEEK_END_DATE)
    INSERT INTO #WeekList values (@WEEK_START_DATE,@WEEK_END_DATE)
    SET @Interval += 1;
    END

SELECT *
FROM #WeekList
ORDER BY Start_Week DESC

DROP TABLE #WeekList

Hasil (5 teratas dan 5 terbawah dari daftar):

Start_Week              End_Week
----------------------- -----------------------
2012-03-12 00:00:00.000 2012-03-18 00:00:00.000
2012-03-05 00:00:00.000 2012-03-11 00:00:00.000
2012-02-27 00:00:00.000 2012-03-04 00:00:00.000
2012-02-20 00:00:00.000 2012-02-26 00:00:00.000
2012-02-13 00:00:00.000 2012-02-19 00:00:00.000
...
2011-01-24 00:00:00.000 2011-01-30 00:00:00.000
2011-01-17 00:00:00.000 2011-01-23 00:00:00.000
2011-01-10 00:00:00.000 2011-01-16 00:00:00.000
2011-01-03 00:00:00.000 2011-01-09 00:00:00.000
2010-12-27 00:00:00.000 2011-01-02 00:00:00.000

Selain itu, Anda juga dapat menggunakan date ketik alih-alih Datetime , jika Anda tidak perlu menyimpan waktu.



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Bagaimana cara mendapatkan tanggal pengelompokan catatan untuk rentang 3 hari dalam SQL?

  2. Sql Server - terhubung dengan otentikasi windows

  3. Filestream di Sql Server 2008 Express

  4. Bagaimana cara memilih string antara dua string dalam kolom di SQL Server?

  5. Isi Dataset Dengan Nama Tabel Dari Prosedur Tersimpan