SQL最有效的查询

时间:2017-12-10 22:36:15

标签: sql sql-server

我在下面的3个表格中创建了两个查询,如果我最有效地执行它们,我只想要某人的意见。

User (**user_id**, group, age, gender, timestamp, activity_type)

Client (**client_id**, sector, specified_age, specified_gender)

Advertise (a**d_id, user_id, client_id, time**, is_click, length)

哪个客户群的广告点击次数最多?

 SELECT c.client_id, c.sector, COUNT(a.is_click) as Clicked_Ads 
    FROM Advertise a, Client c
    WHERE a.client_id = c.client_id
    GROUP BY COUNT(a.is_click)
    ORDER BY c.client_id

女性什么时候最常看广告?

 SELECT a.ad_id, a.client_id, u.user_id, u.timestamps, COUNT(u.timestamps)
    FROM Advertise a, User u
    WHERE u.gender = “Female”, a.user_id = u.user_id
    ORDER BY 
    GROUP BY COUNT(u.timestamps

)

2 个答案:

答案 0 :(得分:1)

您的第一个查询应如下所示:

solutiondir

注意:

  • 使用正确的,明确的SELECT c.sector, COUNT(a.is_click) as Clicked_Ads FROM Advertise a JOIN Client c ON a.client_id = c.client_id GROUP BY c.sector ORDER BY COUNT(a.is_click) DESC LIMIT 1; 语法。 从不JOIN子句中使用逗号。
  • 问题是关于FROMsector条款中不需要任何其他内容。
  • 无论如何,你不能GROUP BY聚合功能。
  • 据推测,您希望GROUP BYORDER BY获得最高权限。

一个问题就足够了。

答案 1 :(得分:0)

查找所有客户端点击次数最多的客户端部门,用于MS SQL服务器

SELECT TOP 1 WITH TIES client_id,sector, Clicked_Ads 
 (
   SELECT c.client_id, c.sector, SUM(a.is_click) as Clicked_Ads 
    FROM Advertise a JOIN Client c
    ON a.client_id = c.client_id
    GROUP BY c.client_id, c.sector
  )T
ORDER BY Clicked_Ads  DESC