选择评分最高,最旧的曲目

时间:2010-03-15 21:12:26

标签: sql sql-server

我有几张桌子:

CREATE TABLE [dbo].[Tracks](
    [Id] [uniqueidentifier] NOT NULL,
    [Artist_Id] [uniqueidentifier] NOT NULL,
    [Album_Id] [uniqueidentifier] NOT NULL,
    [Title] [nvarchar](255) NOT NULL,
    [Length] [int] NOT NULL,
 CONSTRAINT [PK_Tracks_1] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[TrackHistory](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Track_Id] [uniqueidentifier] NOT NULL,
    [Datetime] [datetime] NOT NULL,
 CONSTRAINT [PK_TrackHistory] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]


INSERT INTO [cooltunes].[dbo].[TrackHistory]
           ([Track_Id]
           ,[Datetime])
     VALUES
           ("335294B0-735E-4E2C-8389-8326B17CE813"
           ,GETDATE())



CREATE TABLE [dbo].[Ratings](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Track_Id] [uniqueidentifier] NOT NULL,
    [User_Id] [uniqueidentifier] NOT NULL,
    [Rating] [tinyint] NOT NULL,
 CONSTRAINT [PK_Ratings] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

INSERT INTO [cooltunes].[dbo].[Ratings]
           ([Track_Id]
           ,[User_Id]
           ,[Rating])
     VALUES
           ("335294B0-735E-4E2C-8389-8326B17CE813"
           ,"C7D62450-8BE6-40F6-80F1-A539DA301772"
           ,1)


Users
User_Id|Guid
Other fields

表之间的链接非常明显。

TrackHistory每次播放时都会将每个曲目添加为一行,即。一条轨道会出现在那里很多次。

评级值将为1或-1。

我要做的是选择评分最高的曲目,即more than 2 hours old,以及曲目是否有重复评级(即曲目获得6 + 1评级和1 - 评级,该曲目的总评分为5,另一曲目的总评分为5),应该返回上次播放时间最长的曲目。 (如果在过去2小时内播放了所有曲目,则不应返回任何行)

我正在使用上面的链接[{1}}和SUM(Value)分别对每个部分进行操作,但我无法将它们放在一起。

希望拥有更多(MS)SQL知识的人能够帮助我。非常感谢!

1 个答案:

答案 0 :(得分:1)

select top 1 t.Id, SUM(r.Rating) as Rating, MAX(Datetime) as LastPlayed
from Tracks t
inner join TrackHistory h on t.Id = h.Track_Id
inner join Ratings r on t.Id = r.Track_Id
where h.Track_Id not in (
    select Track_Id 
    from TrackHistory 
    where Datetime > DATEADD(HOUR, -2, getdate())
)
group by t.Id
order by Rating desc, LastPlayed