简体   繁体   English

SQL编写自定义查询

[英]SQL writing custom query

I need to write a SQL Query which generates the name of the most popular story for each user (according to total reading counts). 我需要编写一个SQL查询,它为每个用户生成最受欢迎的故事的名称(根据总读数计数)。 Here is some sample data: 以下是一些示例数据:

story_name | user  | age | reading_counts
-----------|-------|-----|---------------
story 1    | user1 | 4   | 12
story 2    | user2 | 6   | 14
story 4    | user1 | 4   | 15

This is what I have so far but I don't think it's correct: 这是我到目前为止,但我不认为这是正确的:

Select *
From mytable
where (story_name,reading_counts)
IN (Select id, Max(reading_counts)
      FROM mytable
      Group BY user
)
  • In a Derived Table , you can first determine the maximum reading_counts for every user ( Group By with Max() ) 派生表中 ,您可以首先确定每个用户的最大reading_countsGroup By with Max()
  • Now, simply join this result-set to the main table on user and reading_counts , to get the row corresponding to maximum reading_counts for a user. 现在,只需将此结果集连接到userreading_counts上的主表,即可获得与用户的最大reading_counts对应的行。

Try the following query: 请尝试以下查询:

SELECT 
  t1.* 
FROM mytable AS t1 
JOIN 
(
  SELECT t2.user, 
         MAX(t2.reading_counts) AS max_count 
  FROM mytable AS t2
  GROUP BY t2.user 
) AS dt 
  ON dt.user = t1.user AND 
     dt.max_count = t1.reading_counts 
SELECT * 
FROM mytable
WHERE user IN
(SELECT user, max(reading_counts)
FROM mytable
GROUP BY user)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM