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:
Field | Type | Null | Key | Default | Extra |
---|---|---|---|---|---|
topic_id | int(11) | YES | |||
writer_id | int(11) | YES | |||
rated_by | int(11) | YES | |||
date_of_rating | date | YES |
Data:
topic_id | writer_id | rated_by | date_of_rating |
---|---|---|---|
10001 | 504 | 507 | 2020-07-17 |
10003 | 502 | 503 | 2020-09-22 |
10001 | 503 | 507 | 2020-02-07 |
10002 | 501 | 507 | 2020-05-13 |
10002 | 502 | 502 | 2020-04-10 |
10002 | 504 | 502 | 2020-11-16 |
10003 | 501 | 502 | 2020-10-05 |
10001 | 507 | 507 | 2020-12-23 |
10004 | 503 | 501 | 2020-08-28 |
10003 | 505 | 504 | 2020-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.
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
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics