我的查询如下:
SELECT top 8 (OrderTH_strMovieName) as Top8HotFilms,
Convert(char(8), OrderTH_dtmSessionDateTime, 112) as DayOfCount,
count( OrderTH_strMovieName)as filmoccurence
FROM [MOVIES].[dbo].[tblOrderTicketHistory]
where Convert(char(8), OrderTH_dtmSessionDateTime, 112) >=
(SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())))
GROuP BY OrderTH_strMovieName ,
Convert(char(8), OrderTH_dtmSessionDateTime, 112)
ORDER BY filmoccurence desc
结果如下:
Movies Session Day Occurence .tix
*SAN ANDREAS 20150531 2156
*MASSS 20150531 1954
*TOMORROWLAND 20150531 990
SPY 20150531 825
PITCH PERFECT 2 20150531 374
MAD MAX FURY ROAD 20150531 302
*MASSS 20150601 268
*SAN ANDREAS 20150601 257
现在问一下,如何导出一个名为number的列,最终结果如下?
Number Movies Session Day Occurence .tix
1 *SAN ANDREAS 20150531 2156
2 *MASSS 20150531 1954
3 *TOMORROWLAND 20150531 990
4 SPY 20150531 825
5 PITCH PERFECT 2 20150531 374
6 MAD MAX FURY ROAD 20150531 302
7 *MASSS 20150601 268
8 *SAN ANDREAS 20150601 257
答案 0 :(得分:2)
你可以尝试下面的
SELECT top 8 RANK()
OVER (ORDER BY count( OrderTH_strMovieName) desc) AS Number,
(OrderTH_strMovieName) as Top8HotFilms,
Convert(char(8), OrderTH_dtmSessionDateTime, 112) as DayOfCount,
count( OrderTH_strMovieName)as filmoccurence
FROM [MOVIES].[dbo].[tblOrderTicketHistory]
where Convert(char(8), OrderTH_dtmSessionDateTime, 112) >=
(SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())))
GROuP BY OrderTH_strMovieName ,
Convert(char(8), OrderTH_dtmSessionDateTime, 112)
例如:
create table test
(name varchar(10),
age numeric)
insert into test values ('John',10);
insert into test values('Happy',20);
insert into test values ('mary',35);
insert into test values ('mary',35);
insert into test values ('John',10);
SELECT top 2 ROW_NUMBER() over(ORDER BY sum(age)) as number,
name as n,
sum(age) as age_sum
来自测试 按名称分组 按名称排序
number n age_sum
1 Happy 20
2 John 20
答案 1 :(得分:0)
在您的查询中选择ROW NUMBER:https://msdn.microsoft.com/en-us/library/ms186734.aspx
答案 2 :(得分:0)
select top 8 RANK() OVER(ORDER BY moviesHit.filmoccurence ASC) as Rank,
moviesHit.Top8HotFilms,moviesHit.filmoccurence
from
(
SELECT (OrderTH_strMovieName) as Top8HotFilms,
count( OrderTH_strMovieName)as filmoccurence
FROM [MOVIES].[dbo].[tblOrderTicketHistory]
where Convert(char(8), OrderTH_dtmSessionDateTime, 112) >=
(SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())))
GROuP BY OrderTH_strMovieName
) as moviesHit order by moviesHit.filmoccurence ASC