w3resource

SQL Challenges-1: Find all the writers who rated at least one of their own topic

SQL Challenges-1: Exercise-39 with Solution

From the following table write a SQL query to find all the writers who rated at least one of their own topic. Sorted the result in ascending order by writer id. Return writer ID.

Input:

Table: topics

Structure:

FieldTypeNullKeyDefaultExtra
topic_idint(11)YES
writer_idint(11)YES
rated_byint(11)YES
date_of_ratingdateYES

Data:

topic_idwriter_idrated_bydate_of_rating
100015045072020-07-17
100035025032020-09-22
100015035072020-02-07
100025015072020-05-13
100025025022020-04-10
100025045022020-11-16
100035015022020-10-05
100015075072020-12-23
100045035012020-08-28
100035055042020-12-21

Sample Solution:

SQL Code(MySQL):

CREATE TABLE topics (topic_id int, writer_id int, rated_by int, date_of_rating date);
INSERT INTO topics VALUES (10001,504,507,'2020-07-17');
INSERT INTO topics VALUES (10003,502,503,'2020-09-22'); 
INSERT INTO topics VALUES (10001,503,507,'2020-02-07'); 
INSERT INTO topics VALUES (10002,501,507,'2020-05-13'); 
INSERT INTO topics VALUES (10002,502,502,'2020-04-10'); 
INSERT INTO topics VALUES (10002,504,502,'2020-11-16'); 
INSERT INTO topics VALUES (10003,501,502,'2020-10-05'); 
INSERT INTO topics VALUES (10001,507,507,'2020-12-23'); 
INSERT INTO topics VALUES (10004,503,501,'2020-08-28'); 
INSERT INTO topics VALUES (10003,505,504,'2020-12-21');  

SELECT DISTINCT writer_id AS 'Author rated on own topic'  
FROM topics
WHERE writer_id = rated_by
ORDER BY writer_id ;

Sample Output:

Author rated on own topic|
-------------------------|
                      502|
                      507|

SQL Code Editor:


Contribute your code and comments through Disqus.

Previous: Highest purchase for each customer.
Next: Writers who rated more than one topics on the same date.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/sql-exercises/challenges-1/sql-challenges-1-exercise-39.php