我有一张名为tbl_Banners的表。此表存储要在我的网站上显示的横幅。附在此表上的是邮政编码字段(ba_zip_code)。邮政编码用于显示最靠近查看网站的用户的横幅。我还有一个名为tbl_Banners_links的关系表,用于存储不同类型车辆的类别。该表包含以下字段:
bal_id (unique ID), ba_id (banner ID), and vc_id (vehicle category ID)
每个横幅可以有多个车辆类别链接(例如汽车,卡车,SUV等)
我想为某些条件提供评分,包括用户位置的里程,车辆类别和横幅优先级(ba_priority)。
以下是根据此表所示的SQL语句,为每个横幅应用的数据和分数的结果集:
SELECT ba.ba_id, ba.ba_url, ba.ba_filename, bal.vc_id,
(CASE WHEN ba.ba_priority = 1 THEN 40 ELSE 0 END) As ba_priority,
(CASE WHEN bal.vc_id = 1 THEN 50 ELSE 0 END) As vc_id_score,
(CASE
WHEN dbo.CalcDistancebetweenGeoLocations(45.751671, -87.08951, [ba_latitude], [ba_longitude], 0) <= 30 THEN 40
WHEN dbo.CalcDistancebetweenGeoLocations(45.751671, -87.08951, [ba_latitude], [ba_longitude], 0) > 30 AND dbo.CalcDistancebetweenGeoLocations(45.751671, -87.08951, [ba_latitude], [ba_longitude], 0) <= 60 THEN 30
WHEN dbo.CalcDistancebetweenGeoLocations(45.751671, -87.08951, [ba_latitude], [ba_longitude], 0) > 60 AND dbo.CalcDistancebetweenGeoLocations(45.751671, -87.08951, [ba_latitude], [ba_longitude], 0) <= 100 THEN 20
WHEN dbo.CalcDistancebetweenGeoLocations(45.751671, -87.08951, [ba_latitude], [ba_longitude], 0) > 100 THEN 0 ELSE 0 END) As ba_distance
INTO #MyTempBannerTable
FROM tbl_Banners ba
LEFT JOIN tbl_Banners_links bal ON bal.ba_id = ba.ba_id
WHERE ba.ba_active = 1 AND ba.ba_c_id = 1;
评分得分就像这样(或者我想要):
ba_priority = 1 = 40 points
mileage 0-29 = 40 points
mileage 30-59 = 30 points
mileage 60-99 = 20 points
mileage 100+ = 0 points
vc_id = selected vc_id = 50 points
我需要代码根据条件为每个横幅添加所有这些和总计。从下面的结果集中可以看出,如果横幅列出了多个vc_id,则为该特定横幅的每个vc_id分配所有分数。它应该只获取独特的横幅分数。所以横幅广告如下:
mileage 0-29 = 40
ba_priority = 40
vc_id = 50
Total = 130 points
相反,它总共达到了890分。
我需要通过TOTAL SCORE订购,并使用以下代码抓住前5个横幅:
SELECT TOP 5 ba_id, ba_url, ba_filename, SUM(vc_id_score + ba_distance + ba_priority) As RatingScore
FROM #MyTempBannerTable
GROUP BY ba_id, ba_url, ba_filename
ORDER BY RatingScore DESC, NEWID()
以下是结果集:
我希望我有道理并且不会把你和我自己混为一谈。