我正在运行SQL Server 2012
,并且我的数据库中有一个名为DateDimension
的表。
我的DateDimension
表是一个包含2列的表:列date
包含每天从'2014-01-01
'到'2019-12-31
'的日期,列WeekGroup
是{ {1}}数据类型。
摘录如下:
nvarchar(100)
我现在有以下查询:
date WeekGroup
2014-01-01 Wk 30 Dec 2013-05 Jan 2014
2014-01-02 Wk 30 Dec 2013-05 Jan 2014
2014-01-03 Wk 30 Dec 2013-05 Jan 2014
2014-01-04 Wk 30 Dec 2013-05 Jan 2014
2014-01-05 Wk 30 Dec 2013-05 Jan 2014
2014-01-06 Wk 06 Jan 2014-12 Jan 2014
...
我的输出如下:
SELECT
[date],
[WeekGroup],
RANK() OVER (ORDER BY [date] ASC) AS 'Rank'
FROM DateDimension
WHERE date BETWEEN '2014-01-01' AND '2019-12-31'
ORDER BY [date] ASC
我想对上面的查询进行微调,以便获得以下输出,其中包含date WeekGroup Rank
2014-01-01 Wk 30 Dec 2013-05 Jan 2014 1
2014-01-02 Wk 30 Dec 2013-05 Jan 2014 2
2014-01-03 Wk 30 Dec 2013-05 Jan 2014 3
2014-01-04 Wk 30 Dec 2013-05 Jan 2014 4
2014-01-05 Wk 30 Dec 2013-05 Jan 2014 5
2014-01-06 Wk 06 Jan 2014-12 Jan 2014 6
...
distinct
和相应的WeekGroup
:
Rank
如何在WeekGroup Rank
Wk 30 Dec 2013-05 Jan 2014 1
Wk 06 Jan 2014-12 Jan 2014 2
...
变量(nvarchar
)上执行此操作?
答案 0 :(得分:0)
按周分组保留date
并进行汇总:
SELECT WeekGroup,
RANK() OVER (ORDER BY MIN([date]) ASC) AS [Rank]
FROM DateDimension
WHERE date BETWEEN '2014-01-01' AND '2019-12-31'
GROUP BY WeekGroup
ORDER BY MIN([date]) ASC;
答案 1 :(得分:0)
这使用CTE和RANK():
declare @DateDimension table ([date] date, WeekGroup nvarchar(100))
insert into @DateDimension values
('2014-01-01', 'Wk 30 Dec 2013-05 Jan 2014')
, ('2014-01-02', 'Wk 30 Dec 2013-05 Jan 2014')
, ('2014-01-03', 'Wk 30 Dec 2013-05 Jan 2014')
, ('2014-01-04', 'Wk 30 Dec 2013-05 Jan 2014')
, ('2014-01-05', 'Wk 30 Dec 2013-05 Jan 2014')
, ('2014-01-06', 'Wk 06 Jan 2014-12 Jan 2014')
;with cte as (
SELECT [WeekGroup], count(*) as count
FROM @DateDimension
WHERE date BETWEEN '2014-01-01' AND '2019-12-31'
group by [WeekGroup])
select [WeekGroup], rank() over (order by [count] desc) as [Rank] from cte
答案 2 :(得分:-1)
尝试一下。
declare @DatA table ([date] date, WeekGroup nvarchar(100))
insert into @DatA values
('2014-01-01', 'Wk 30 Dec 2013-05 Jan 2014')
, ('2014-01-02', 'Wk 30 Dec 2013-05 Jan 2014')
, ('2014-01-03', 'Wk 30 Dec 2013-05 Jan 2014')
, ('2014-01-04', 'Wk 30 Dec 2013-05 Jan 2014')
, ('2014-01-05', 'Wk 30 Dec 2013-05 Jan 2014')
, ('2014-01-06', 'Wk 06 Jan 2014-12 Jan 2014')
SELECT WEEKGROUP, RANK() OVER (ORDER BY A.WeekGroup desc) RNK
FROM (
SELECT DISTINCT WEEKGROUP FROM @DatA
WHERE date BETWEEN '2014-01-01' AND '2019-12-31'
)A