我的第一个问题:
`SELECT M.type, U.campaign_id, count(*) as NumEvents
FROM dbo.Events E
JOIN dbo.Meals M
ON E.meal_id = M.meal_id
JOIN dbo.Users U
ON U.userid = E.userid
GROUP BY M.type, U.campaign_id
ORDER BY M.type`
这给了我这个结果:
TYPE Campaign-id # of Events
Chinese FB 2
Chinese RE 1
Chinese TW 2
French FB 1
French PI 2
French RE 2
Italian FB 3
Italian RE 2
Italian TW 2
Mexican RE 1
如果类型是膳食的类型,则Campaign_id指的是吃饭的人的类型,并且#个事件是指具有特定Campaign_id的人吃了某种类型的膳食的次数。
我需要一个SQL Server查询,它会为我提供与每种膳食类型的大多数事件相关联的Campaign_id。谢谢
结果应如下所示:
TYPE Campaign-id with Greatest Number of events
Chinese FB or TW
French RE or PI
Italian FB
Mexican RE
答案 0 :(得分:1)
首先,简化您现有的查询:
SELECT m.type, U.campaign_id, count(*) as NumEvents
FROM dbo.Events E JOIN
dbo.Meals M
ON E.meal_id = M.meal_id JOIN
dbo.Users U
ON U.userid = E.userid
GROUP BY m.type, U.campaign_id;
然后,让我们解决这个问题,以获得你想要的东西:
SELECT mc.*
FROM (SELECT m.type, U.campaign_id, count(*) as NumEvents,
ROW_NUMBER() OVER (PARTITION BY m.type ORDER BY COUNT(*) DESC) as seqnum
FROM dbo.Events E JOIN
dbo.Meals M
ON E.meal_id = M.meal_id JOIN
dbo.Users U
ON U.userid = E.userid
GROUP BY m.type, U.campaign_id
) mc
WHERE seqnum = 1;