我是新手,我需要广告/营销机构数据库的帮助
我有两个表,一个是 List_of_billboards ,它具有三列:Billboard_ID(PK),位置和类型,第二个是 Billboard_Ad_Campaigns ,它具有四列:Ad_ID (PK),Cost_of_campaign,ID_of_client,Billboard_ID(FK)。
表中的数据如下:
表1:
Billboard_ID | Location | Type
BbID001 | London | Digital
BbID002 | Hayward | 3D
BbID003 | Las Vegas | Painted
BbID004 | New York | Painted
表2:
Ad_ID | Cost_of_campaign | ID_of_client | Billboard_ID
BbCID0001 $123 001 BbID001
BbCID0002 $456 002 BbID002
BbCID0003 $789 003 BbID003
BbCID0004 $1234 003 BbID004
我如何找到某种广告牌(3D,数字,绘画等)的最高/最低成本?
例如,根据上述数据,涂漆成本最高的广告牌将是BbID004(纽约为一)
答案 0 :(得分:2)
使用窗口功能。对于最便宜的广告系列:
select b.*
from (select t2.*,
row_number() over (partition by t1.type order by t2.cost_of_campaign asc) as seqnum
from table1 t1 join
table2 t2
on t1.Billboard_ID = t2.Billboard_ID
) b
where seqnum = 1
答案 1 :(得分:0)
select t1.type,
max(t2.cost_of_campaign) max_cost_of_campaign,
min(t2.cost_of_campaign) min_cost_of_campaign
from table1 t1
join table2 t2
on t1.Billboard_ID = t2.Billboard_ID
group by t1.type
https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=5abc548aa178a82a9f6f33527fa5c265
或者如果需要,可以使用窗口函数和first_value来获取max和min中的其他列
select distinct t1.type,
first_value(t1.Billboard_ID) over (partition by t1.type order by t2.cost_of_campaign desc) max_Billboard_ID,
max(t2.cost_of_campaign) over (partition by t1.type) max_cost_of_campaign,
first_value(t1.Billboard_ID) over (partition by t1.type order by t2.cost_of_campaign asc) min_Billboard_ID,
min(t2.cost_of_campaign) over (partition by t1.type) min_cost_of_campaign
from table1 t1
join table2 t2
on t1.Billboard_ID = t2.Billboard_ID
https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=887b95cb041b1d6fb37ccfb47aabd3ea