1

所以我想做的是做一个趋势算法,我需要 SQL 代码的帮助,因为我不能让它去。

该算法有三个方面:(我对更好的趋势算法的想法完全开放)

1.Plays during 24h / Total plays of the song
2.Plays during 7d / Total plays of the song 
3.Plays during 24h / The value of plays of the most played item over 24h (whatever item leads the play count over 24h)

每个方面的值应为 0.33,最大值为 1.0 是可能的。

第三个方面是必要的,因为新上传的项目将自动排在首位,除非它们是一种将它们放下的方式。

该表称为 aud_plays 列是:

PlayID: Just an auto-incrementing ID for the table
AID: The id of the song
IP: ip address of the user listening
time: UNIX time code

我已经尝试了一些 sql 代码,但我非常坚持无法让它工作。

4

1 回答 1

1

In your ?aud_songs? (the one the AID points to) table add the following columns

  • Last24hrPlays INT -- use BIGINT if you plan on getting billion+
  • Last7dPlays INT
  • TotalPlays INT

In your aud_plays table create an AFTER INSERT trigger that will increment aud_song.TotalPlays.

UPDATE aud_song SET TotalPlays = TotalPlays + 1 WHERE id = INSERTED.aid

Calculating your trending in real time for every request would be taxing on your server, so it's best to just run a job to update the data every ~5 minutes. So create a SQL Agent Job to run every X minutes that updates Last7dPlays and Last24hrPlays.

UPDATE aud_songs SET Last7dPlays = (SELECT COUNT(*) FROM aud_plays WHERE aud_plays.aid = aud_songs.id AND aud_plays.time BETWEEN GetDate()-7 AND GetDate()), 
    Last24hrPlays = (SELECT COUNT(*) FROM aud_plays WHERE aud_plays.aid = aud_songs.id AND aud_plays.time BETWEEN GetDate()-1 AND GetDate())

I would also recommend removing old records from aud_plays (possibly older than 7days since you will have the TotalPlays trigger.

It should be easy to figure out how to calculate your 1 and 2 (from the question). Here's the SQL for 3.

SELECT cast(Last24hrPlays as float) / (SELECT MAX(Last24hrPlays) FROM aud_songs) FROM aud_songs WHERE aud_songs.id = @ID

NOTE I made the T-SQL pretty generic and unoptimized to illustrate how the process works.

于 2012-02-15T14:14:18.437 回答