{"id":15003285,"url":"https://github.com/kleamertiri/leetcode-sql-questions","last_synced_at":"2026-02-06T00:32:12.191Z","repository":{"id":154638129,"uuid":"623465962","full_name":"kleamertiri/LeetCode-SQL-Questions","owner":"kleamertiri","description":null,"archived":false,"fork":false,"pushed_at":"2025-02-04T19:29:11.000Z","size":255,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-12T04:26:26.111Z","etag":null,"topics":["ms-sql-server","sql"],"latest_commit_sha":null,"homepage":"https://leetcode.com/","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kleamertiri.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-04-04T12:33:42.000Z","updated_at":"2025-02-04T19:29:14.000Z","dependencies_parsed_at":null,"dependency_job_id":"b8b75bbf-5a39-48b1-87be-c02de4e14a87","html_url":"https://github.com/kleamertiri/LeetCode-SQL-Questions","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/kleamertiri/LeetCode-SQL-Questions","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kleamertiri%2FLeetCode-SQL-Questions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kleamertiri%2FLeetCode-SQL-Questions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kleamertiri%2FLeetCode-SQL-Questions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kleamertiri%2FLeetCode-SQL-Questions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kleamertiri","download_url":"https://codeload.github.com/kleamertiri/LeetCode-SQL-Questions/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kleamertiri%2FLeetCode-SQL-Questions/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":265573572,"owners_count":23790466,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ms-sql-server","sql"],"created_at":"2024-09-24T18:57:52.264Z","updated_at":"2026-02-06T00:32:12.103Z","avatar_url":"https://github.com/kleamertiri.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# 🔸LeetCode SQL Questions\n[LeetCode](https://leetcode.com/) is the platform to expand your knowledge and prepare for technical interviews.\n\nHere you'll find my SQL solutions in MS SQL Server.\n\n\u003cdetails\u003e\n     \u003csummary\u003e:green_circle:Level: Easy\u003c/summary\u003e\n\n## Solved:heavy_check_mark: \n    \n#### :zap:[1873. Calculate Special Bonus](https://leetcode.com/problems/calculate-special-bonus/)\nWrite an SQL query to calculate the bonus of each employee. The bonus of an employee is ```100%``` of their salary if the ID of the employee is **an odd number** and **the employee name does not start with the character** ```'M'```. The bonus of an employee is ```0``` otherwise.\nReturn the result table ordered by ```employee_id```.\n```sql\nSELECT employee_id, \nCASE\n    WHEN employee_id % 2 != 0 AND NAME NOT LIKE 'M%' THEN salary\n    ELSE 0\nEND AS bonus\nFROM Employees\nORDER BY employee_id;\n```\n**Output:**\n| employee_id | bonus |\n| ----------- | ----- |\n| 2           | 0     |\n| 3           | 0     |\n| 7           | 7400  |\n| 8           | 0     |\n| 9           | 7700  |\n\n#### :zap:[610. Triangle Judgement](https://leetcode.com/problems/triangle-judgement/)\nWrite an SQL query to report for every three line segments whether they can form a triangle.\nReturn the result table in **any order**.\n```sql\nSELECT x, y, z,\nCASE \n    WHEN x + y \u003e z AND x + z \u003e y AND z + y \u003e x THEN 'Yes'\n    ELSE 'No'\nEND AS triangle\nFROM Triangle;\n```\n\n**Output:**\n| x  | y  | z  | triangle |\n| -- | -- | -- | -------- |\n| 13 | 15 | 30 | No       |\n| 10 | 20 | 15 | Yes      |\n\n#### :zap:[196. Delete Duplicate Emails](https://leetcode.com/problems/delete-duplicate-emails/)\nWrite an SQL query to **delete** all the duplicate emails, keeping only one unique email with the smallest ```id```. Note that you are supposed to write a ```DELETE``` statement and not a ```SELECT``` one.\n\n```sql\nDELETE P1\nFROM Person P1, Person P2\nWHERE P1.email = P2.Email AND P1.Id \u003e P2.Id;\n```\n**Output:**\n| id | email            |\n| -- | ---------------- |\n| 1  | john@example.com |\n| 2  | bob@example.com  |\n\n\n#### :zap:[1280. Students and Examinations](https://leetcode.com/problems/students-and-examinations/) \nWrite an SQL query to find the number of times each student attended each exam.\nReturn the result table ordered by **student_id** and **subject_name**.\n```sql\n\nSELECT st.student_id, st.student_name, sb.subject_name, COUNT(exam.subject_name) AS attended_exams\nFROM Students AS st\nCROSS JOIN Subjects AS sb\nLEFT JOIN Examinations AS exam\nON st.student_id = exam.student_id AND sb.subject_name = exam.subject_name\nGROUP BY st.student_id, st.student_name, sb.subject_name\n\n```\n**Output:**\n| student_id | student_name | subject_name | attended_exams |\n| ---------- | ------------ | ------------ | -------------- |\n| 1          | Alice        | Math         | 3              |\n| 1          | Alice        | Physics      | 2              |\n| 1          | Alice        | Programming  | 1              |\n| 2          | Bob          | Math         | 1              |\n| 2          | Bob          | Physics      | 0              |\n| 2          | Bob          | Programming  | 1              |\n| 6          | Alex         | Math         | 0              |\n| 6          | Alex         | Physics      | 0              |\n| 6          | Alex         | Programming  | 0              |\n| 13         | John         | Math         | 1              |\n| 13         | John         | Physics      | 1              |\n| 13         | John         | Programming  | 1              |\n\n\n\n#### :zap:[1211.Queries Quality and Percentage](https://leetcode.com/problems/queries-quality-and-percentage/)\nWe define ```query``` quality as:\n```The average of the ratio between query rating and its position.```\nWe also define ```poor query percentage``` as:\n```The percentage of all queries with rating less than 3.```\nWrite an SQL query to find each ```query_name```, the ```quality``` and ```poor_query_percentage```.\nBoth ```quality``` and ```poor_query_percentage``` should be **rounded to 2 decimal places**.\n```sql\nSELECT query_name,\n        ROUND(SUM(rating / CONVERT(DECIMAL(5,2), position)) / COUNT(query_name),2) AS quality,\n        ROUND(SUM(IIF(RATING \u003c 3, 1, 0)) * 100 /CONVERT(DECIMAL(5,2),COUNT(query_name)), 2)  AS poor_query_percentage\n\nFROM Queries\nGROUP BY query_name;\n```\n**Output:**\n| query_name | quality | poor_query_percentage |\n| ---------- | ------- | --------------------- |\n| Cat        | 0.66    | 33.33                 |\n| Dog        | 2.5     | 33.33                 |\n\n#### :zap:[619.Biggest Single Number](https://leetcode.com/problems/biggest-single-number/)\nA **single number** is a number that appeared only once in the ```MyNumbers``` table.\nWrite an SQL query to report the largest **single number**. If there is no single number, report ```null```.\n```sql\nSELECT MAX(x.num) AS num\nFROM(\n  SELECT num, COUNT(num) AS count_num\n  FROM MyNumbers\n  GROUP BY num\n  HAVING COUNT(num) \u003c 2\n) AS x\n```\n\n**Output:**\n| num |\n| --- |\n| 6   |\n\n#### :zap:[1179. Reformat Department Table](https://leetcode.com/problems/reformat-department-table/)\nWrite an SQL query to reformat the table such that there is a department id column and a revenue column **for each month**.\n```sql\nSELECT  id, \nSUM(IIF(month = 'Jan', revenue, NULL)) AS Jan_Revenue,\nSUM(IIF(month = 'Feb', revenue, NULL)) AS Feb_Revenue,\nSUM(IIF(month = 'Mar', revenue, NULL)) AS Mar_Revenue,\nSUM(IIF(month = 'Apr', revenue, NULL)) AS Apr_Revenue,\nSUM(IIF(month = 'May', revenue, NULL)) AS May_Revenue,\nSUM(IIF(month = 'Jun', revenue, NULL)) AS Jun_Revenue,\nSUM(IIF(month = 'Jul', revenue, NULL)) AS Jul_Revenue,\nSUM(IIF(month = 'Aug', revenue, NULL)) AS Aug_Revenue,\nSUM(IIF(month = 'Sep', revenue, NULL)) AS Sep_Revenue,\nSUM(IIF(month = 'Oct', revenue, NULL)) AS Oct_Revenue,\nSUM(IIF(month = 'Nov', revenue, NULL)) AS Nov_Revenue,\nSUM(IIF(month = 'Dec', revenue, NULL)) AS Dec_Revenue\nFROM Department\nGROUP BY id;\n```\n**Output:**\n\n| id | Jan_Revenue | Feb_Revenue | Mar_Revenue | Apr_Revenue | May_Revenue | Jun_Revenue | Jul_Revenue | Aug_Revenue | Sep_Revenue | Oct_Revenue | Nov_Revenue | Dec_Revenue |\n| -- | ----------- | ----------- | ----------- | ----------- | ----------- | ----------- | ----------- | ----------- | ----------- | ----------- | ----------- | ----------- |\n| 1  | 8000        | 7000        | 6000        | null        | null        | null        | null        | null        | null        | null        | null        | null        |\n| 2  | 9000        | null        | null        | null        | null        | null        | null        | null        | null        | null        | null        | null        |\n| 3  | null        | 10000       | null        | null        | null        | null        | null        | null        | null        | null        | null        | null        |\n\n#### :zap:[1141. User Activity for the Past 30 Days I](https://leetcode.com/problems/user-activity-for-the-past-30-days-i/)\nWrite an SQL query to find the daily active user count for a period of ```30``` days ending ```2019-07-27``` inclusively. A user was active on someday if they made at least one activity on that day.\n```sql\nSELECT activity_date AS day, COUNT(DISTINCT user_id) AS active_users\nFROM Activity\nWHERE activity_date between DATEADD(day, -29, '2019-07-27') AND '2019-07-27'\nGROUP BY activity_date\nHAVING COUNT(DISTINCT user_id) \u003e 0;\n```\n**Output:**\n| day        | active_users |\n| ---------- | ------------ |\n| 2019-07-20 | 2            |\n| 2019-07-21 | 2            |\n\n#### :zap:[1084. Sales Analysis III](https://leetcode.com/problems/sales-analysis-iii/)\nWrite an SQL query that reports the **products** that were **only** sold in the first quarter of ```2019```. That is, between ```2019-01-01``` and ```2019-03-31``` inclusive.\n\n```sql\nSELECT  DISTINCT S.product_id,P.product_name\nFROM Sales AS S\nLEFT JOIN Product AS P\nON s.product_id = p.product_id\nWHERE S.product_id NOT IN (SELECT product_id\n                          FROM Sales\n                          WHERE sale_date \u003c '2019-01-01' or sale_date \u003e '2019-03-31')\n```\n\n**Output:**\n| product_id | product_name |\n| ---------- | ------------ |\n| 1          | S8           |\n\n#### :zap:[1667. Fix Names in a Table](https://leetcode.com/problems/fix-names-in-a-table/)\nWrite an SQL query to fix the names so that only the first character is uppercase and the rest are lowercase.\nReturn the result table ordered by ```user_id```.\n```sql\nSELECT user_id, (UPPER(LEFT(name, 1)) + LOWER(SUBSTRING(name, 2, LEN(name)))) AS name\nFROM Users\nORDER BY user_id;\n```\n**Output:**\n| user_id | name  |\n| ------- | ----- |\n| 1       | Alice |\n| 2       | Bob   |\n\n#### :zap:[181. Employees Earning More Than Their Managers](https://leetcode.com/problems/employees-earning-more-than-their-managers/)\nWrite an SQL query to find the employees who earn more than their managers.\n```sql\nSELECT name AS Employee\nFROM Employee as e\nWHERE salary \u003e (SELECT salary FROM Employee  WHERE id = e.managerID)\n```\n**Output:**\n| Employee |\n| -------- |\n| Joe      |\n\n#### :zap:[182. Duplicate Emails](https://leetcode.com/problems/duplicate-emails/)\nWrite an SQL query to report all the duplicate emails. Note that it's guaranteed that the email field is not NULL.\n```sql\nSELECT email\nFROM Person\nGROUP BY email\nHAVING COUNT(email) \u003e 1; \n```\n**Output:**\n| email   |\n| ------- |\n| a@b.com |\n\n#### :zap:[183. Customers Who Never Order](https://leetcode.com/problems/customers-who-never-order/)\nWrite an SQL query to report all customers who never order anything.\n```sql\nSELECT C.name AS Customers\nFROM Customers AS C\nLEFT JOIN Orders AS O\nON C.id = O.customerId\nWHERE O.id IS NULL;\n```\n**Output:**\n| Customers |\n| --------- |\n| Henry     |\n| Max       |\n\n#### :zap:[197. Rising Temperature](https://leetcode.com/problems/rising-temperature/)\nWrite an SQL query to find all dates' ```Id``` with higher temperatures compared to its previous dates (yesterday).\n```sql\nSELECT w.id AS Id\nFROM Weather w\nJOIN Weather yesterday\nON DATEDIFF(DAY, yesterday.recordDate, w.recordDate) = 1\nWHERE w.temperature \u003e yesterday.temperature;\n```\n**Output:**\n| Id |\n| -- |\n| 2  |\n| 4  |\n\n#### :zap:[577. Employee Bonus](https://leetcode.com/problems/employee-bonus/)\nWrite an SQL query to report the name and bonus amount of each employee with a bonus **less than** ```1000```.\n\n```sql\nSELECT E.name, B.bonus\nFROM Employee AS E\nLEFT JOIN Bonus AS B\nON E.empId = B.empId\nWHERE B.bonus \u003c 1000 OR B.bonus IS NULL;\n```\n**Output:**\n| name | bonus |\n| ---- | ----- |\n| Brad | null  |\n| John | null  |\n| Dan  | 500   |\n\n#### :zap:[584. Find Customer Referee](https://leetcode.com/problems/find-customer-referee/)\nWrite an SQL query to report the names of the customer that are not referred by the customer with ```id = 2```.\n```sql\nSELECT name\nFROM Customer\nWHERE referee_id != 2 OR referee_id IS NULL;\n```\n**Output:**\n| name |\n| ---- |\n| Will |\n| Jane |\n| Bill |\n| Zack |\n\n#### :zap:[586. Customer Placing the Largest Number of Orders](https://leetcode.com/problems/customer-placing-the-largest-number-of-orders/)\nWrite an SQL query to find the ```customer_number``` for the customer who has placed **the largest number of orders**.\nThe test cases are generated so that **exactly one customer** will have placed more orders than any other customer.\n\n```sql\nSELECT TOP 1 customer_number\nFROM Orders\nGROUP BY customer_number\nORDER BY COUNT(customer_number) DESC;\n```\n**Output:**\n| customer_number |\n| --------------- |\n| 3               |\n\n#### :zap:[607. Sales Person](https://leetcode.com/problems/sales-person/)\nWrite an SQL query to report the names of all the salespersons who did not have any orders related to the company with the name **\"RED\"**.\n```sql\nSELECT  DISTINCT S.name\nFROM SalesPerson AS S\nLEFT JOIN Orders AS O\nON S.sales_id = O.sales_id\nWHERE S.sales_id NOT IN (\n    SELECT DISTINCT o.sales_id\n    FROM Orders o\n    INNER JOIN Company c ON o.com_id = c.com_id\n    WHERE c.name = 'RED'\n)\n```\n**Output:**\n| name |\n| ---- |\n| Alex |\n| Amy  |\n| Mark |\n\n#### :zap:[620. Not Boring Movies](https://leetcode.com/problems/not-boring-movies/)\nWrite an SQL query to report the movies with an odd-numbered ID and a description that is not ```\"boring\"```.\nReturn the result table ordered by ```rating``` **in descending order**.\n```sql\nSELECT *\nFROM Cinema\nWHERE id % 2 != 0 AND description NOT IN (\n  SELECT description FROM Cinema WHERE description = 'boring'\n)\nORDER BY rating DESC;\n```\n**Output:**\n| id | movie      | description | rating |\n| -- | ---------- | ----------- | ------ |\n| 5  | House card | Interesting | 9.1    |\n| 1  | War        | great 3D    | 8.9    |\n\n#### :zap:[1050. Actors and Directors Who Cooperated At Least Three Times](https://leetcode.com/problems/actors-and-directors-who-cooperated-at-least-three-times/)\nWrite a SQL query for a report that provides the pairs ```(actor_id, director_id)``` where the actor has cooperated with the director at least three times.\n```sql\nSELECT actor_id, director_id\nFROM ActorDirector\nGROUP BY actor_id, director_id\nHAVING COUNT(actor_id)\u003e=3;\n```\n**Output:**\n| actor_id | director_id |\n| -------- | ----------- |\n| 1        | 1           |\n\n#### :zap:[1075. Project Employees I](https://leetcode.com/problems/project-employees-i/)\nWrite an SQL query that reports the **average** experience years of all the employees for each project, **rounded to 2 digits**.\n```sql\nSELECT p.project_id, ROUND(AVG(CAST(e.experience_years AS decimal(5,2))), 2) AS  average_years\nFROM Project AS p\nJOIN Employee AS e\nON p.employee_id = e.employee_id\nGROUP BY p.project_id;\n```\n**Output:**\n| project_id | average_years |\n| ---------- | ------------- |\n| 1          | 2             |\n| 2          | 2.5           |\n\n#### :zap:[1148. Article Views I](https://leetcode.com/problems/article-views-i/)\nWrite an SQL query to find all the authors that viewed at least one of their own articles.\nReturn the result table sorted by ```id``` in ascending order.\n\n```sql\nSELECT DISTINCT author_id AS id\nFROM Views\nWHERE author_id = viewer_id;\n```\n**Output:**\n| id |\n| -- |\n| 4  |\n| 7  |\n\n#### :zap:[1251. Average Selling Price](https://leetcode.com/problems/average-selling-price/)\nWrite an SQL query to find the average selling price for each product. ```average_price``` should be **rounded to 2 decimal places**.\n```sql\nSELECT p.product_id, ROUND(SUM(p.price * u.units) / CONVERT(decimal(7,2), SUM(u.units)), 2) AS average_price\nFROM Prices AS p\nJOIN UnitsSold AS u \nON p.product_id = u.product_id\nWHERE u.purchase_date between p.start_date AND p.end_date\nGROUP BY p.product_id;\n```\n**Output:**\n| product_id | average_price |\n| ---------- | ------------- |\n| 1          | 6.96          |\n| 2          | 16.96         |\n\n#### :zap:[1327. List the Products Ordered in a Period](https://leetcode.com/problems/list-the-products-ordered-in-a-period/)\n```sql\nWITH CTE_unit AS (\n  SELECT p.product_name, SUM(o.unit) AS unit\n  FROM Products AS p\n  JOIN Orders AS o\n  ON p.product_id = o.product_id\n  WHERE MONTH(o.order_date) = '02' AND YEAR(o.order_date) = '2020' \n  GROUP BY p.product_name\n)\n\nSELECT *\nFROM CTE_unit\nWHERE unit \u003e=100\n```\n\n**Output:**\n| product_name       | unit |\n| ------------------ | ---- |\n| Leetcode Kit       | 100  |\n| Leetcode Solutions | 130  |\n\n#### :zap:[1484. Group Sold Products By The Date](https://leetcode.com/problems/group-sold-products-by-the-date/)\nWrite an SQL query to find for each date the number of different products sold and their names.\nThe sold products names for each date should be sorted lexicographically.\nReturn the result table ordered by ```sell_date```.\n```sql\nwith CTE_DISTINCT AS\n(\n    SELECT DISTINCT sell_date, product\n    FROM Activities\n)\n\nSELECT sell_date, COUNT(DISTINCT product) AS num_sold, STRING_AGG(product, ',') WITHIN GROUP (ORDER BY product) AS products\nFROM CTE_DISTINCT\nGROUP BY sell_date\nORDER BY sell_date;\n```\n**Output:**\n| sell_date  | num_sold | products                     |\n| ---------- | -------- | ---------------------------- |\n| 2020-05-30 | 3        | Basketball,Headphone,T-Shirt |\n| 2020-06-01 | 2        | Bible,Pencil                 |\n| 2020-06-02 | 1        | Mask                         |\n\n#### :zap:[1527. Patients With a Condition](https://leetcode.com/problems/patients-with-a-condition/)\nWrite an SQL query to report the patient_id, patient_name and conditions of the patients who have Type I Diabetes. Type I Diabetes always starts with ```DIAB1``` prefix.\n\n```sql\nSELECT patient_id, patient_name, conditions\nFROM Patients\nWHERE conditions LIKE 'DIAB1%' OR conditions LIKE '% DIAB1%' OR conditions LIKE '%DIAB1';\n```\n**Output:**\n| patient_id | patient_name | conditions   |\n| ---------- | ------------ | ------------ |\n| 3          | Bob          | DIAB100 MYOP |\n| 4          | George       | ACNE DIAB100 |\n\n#### :zap:[1795. Rearrange Products Table](https://leetcode.com/problems/rearrange-products-table/)\nWrite an SQL query to rearrange the ```Products``` table so that each row has ```(product_id, store, price)```. If a product is not available in a store, do **not** include a row with that ```product_id``` and ```store``` combination in the result table.\n```sql\nSELECT product_id, 'store1' AS store, store1 AS price\nFROM Products\nWHERE store1 IS NOT NULL\nUNION \nSELECT product_id, 'store2' AS store, store2 AS price\nFROM Products\nWHERE store2 IS NOT NULL\nUNION \nSELECT product_id, 'store3' AS store, store3 AS price\nFROM Products\nWHERE store3 IS NOT NULL;\n```\n**Output:**\n| product_id | store  | price |\n| ---------- | ------ | ----- |\n| 0          | store1 | 95    |\n| 0          | store2 | 100   |\n| 0          | store3 | 105   |\n| 1          | store1 | 70    |\n| 1          | store3 | 80    |\n\n\n#### :zap:[1965. Employees With Missing Information](https://leetcode.com/problems/employees-with-missing-information/)\nWrite an SQL query to report the IDs of all the employees with **missing information**. The information of an employee is missing if:\n- The employee's **name** is missing, or\n- The employee's **salary** is missing.\nReturn the result table ordered by ```employee_id``` in **ascending order**.\n```sql\n--1--\nSELECT employee_id\nFROM Employees\nWHERE employee_id NOT IN (SELECT employee_id FROM Salaries)\n\nUNION\n\nSELECT employee_id\nFROM Salaries\nWHERE employee_id NOT IN (SELECT employee_id FROM Employees)\nORDER BY employee_id;\n\n--2--\nSELECT concat(e.employee_id, s.employee_id) AS employee_id\nFROM Employees AS e\nFULL JOIN Salaries AS s\nON e.employee_id = s.employee_id\nWHERE name IS NULL OR salary IS NULL\nORDER BY 1 ASC;\n```\n     \n**Output:**\n| employee_id |\n| ----------- |\n| 1           |\n| 2           |\n\n#### :zap:[1517. Find Users With Valid E-Mails](https://leetcode.com/problems/find-users-with-valid-e-mails/description/)\nWrite an SQL query to find the users who have **valid emails**.\nA valid e-mail has a prefix name and a domain where:\n\n- **The prefix name** is a string that may contain letters (upper or lower case), digits, underscore `'_'`, period `'.'`, and/or dash `'-'`. The prefix name must start with a letter.\n- The domain is `'@leetcode.com'`.\n```sql\nSELECT user_id, name, mail FROM Users \nWHERE mail LIKE '[a-z]%@leetcode.com' \nAND user_id NOT IN (SELECT user_id FROM Users WHERE mail LIKE '%[^a-z0-9._-]%@leetcode.com')\n```\n**Output:**\n| user_id | name      | mail                    |\n| ------- | --------- | ----------------------- |\n| 1       | Winston   | winston@leetcode.com    |\n| 3       | Annabelle | bella-@leetcode.com     |\n| 4       | Sally     | sally.come@leetcode.com |\n     \n#### :zap:[1581. Customer Who Visited but Did Not Make Any Transactions](https://leetcode.com/problems/customer-who-visited-but-did-not-make-any-transactions/description/)\nWrite a SQL query to find the IDs of the users who visited without making any transactions and the number of times they made these types of visits.\n```sql\nSELECT v.customer_id, COUNT(v.visit_id) AS count_no_trans\nFROM Visits AS v\nLEFT JOIN Transactions AS t\nON v.visit_id = t.visit_id\nWHERE t.amount is null\nGROUP BY v.customer_id;\n```\n**Output:**\n| customer_id | count_no_trans |\n| ----------- | -------------- |\n| 30          | 1              |\n| 54          | 2              |\n| 96          | 1              |\n\n#### :zap:[1587. Bank Account Summary II](https://leetcode.com/problems/bank-account-summary-ii/description/)\nWrite an SQL query to report the name and balance of users with a balance higher than `10000`. The balance of an account is equal to the sum of the amounts of all transactions involving that account.\n\n```sql\nWITH CTE_balance AS (\n    SELECT u.name, SUM(t.amount) AS balance\n    FROM Users AS u\n    JOIN Transactions AS t\n    ON u.account = t.account\n    GROUP BY u.name\n)\n\nSELECT * \nFROM CTE_balance\nWHERE balance \u003e 10000;\n```\n\n**Output:**\n| name  | balance |\n| ----- | ------- |\n| Alice | 11000   |\n\n#### :zap:[1661. Average Time of Process per Machine](https://leetcode.com/problems/average-time-of-process-per-machine/description/)\nThere is a factory website that has several machines each running the **same number of processes**. Write an SQL query to find the **average time** each machine takes to complete a process.\n\nThe time to complete a process is the `'end' timestamp` minus the `'start' timestamp`. The average time is calculated by the total time to complete every process on the machine divided by the number of processes that were run.\n\nThe resulting table should have the `machine_id` along with the **average time** as `processing_time`, which should be **rounded to 3 decimal places**.\n\n```sql\nSELECT machine_id, \n      ROUND((SUM(CASE WHEN activity_type = 'end' THEN timestamp END)-SUM(CASE WHEN activity_type = 'start' THEN timestamp END)) / COUNT(DISTINCT process_id), 3) \n      AS  processing_time\nFROM Activity\nGROUP BY machine_id  \n```\n     \n**Output:**\n \n| machine_id | processing_time |\n| ---------- | --------------- |\n| 0          | 0.894           |\n| 1          | 0.995           |\n| 2          | 1.456           |\n\n     \n#### :zap:[1693. Daily Leads and Partners](https://leetcode.com/problems/daily-leads-and-partners/)\nWrite an SQL query that will, for each `date_id` and `make_name`, return the number of **distinct** `lead_id`'s and **distinct** `partner_id`'s.\n\n```sql\nSELECT date_id, make_name, COUNT(DISTINCT lead_id) AS unique_leads, COUNT(DISTINCT partner_id) AS unique_partners\nFROM DailySales\nGROUP BY date_id, make_name;\n```\n     \n**Output:**\n| date_id    | make_name | unique_leads | unique_partners |\n| ---------- | --------- | ------------ | --------------- |\n| 2020-12-07 | honda     | 3            | 2               |\n| 2020-12-07 | toyota    | 1            | 2               |\n| 2020-12-08 | honda     | 2            | 2               |\n| 2020-12-08 | toyota    | 2            | 3               |\n\n#### :zap:[1789. Primary Department for Each Employee](https://leetcode.com/problems/primary-department-for-each-employee/)\nEmployees can belong to multiple departments. When the employee joins other departments, they need to decide which department is their primary department. Note that when an employee belongs to only one department, their primary column is `'N'`.\n\nWrite an SQL query to report all the employees with their primary department. For employees who belong to one department, report their only department.     \n```sql\nWITH CTE_count AS (\n  SELECT *,  COUNT(*) OVER(PARTITION BY employee_id) AS nr_emp_id\nFROM Employee \n)\n\nSELECT employee_id, department_id\nFROM CTE_count\nWHERE nr_emp_id = 1 OR (nr_emp_id \u003e 1 AND primary_flag = 'Y')\n```\n\n**Output:**\n| employee_id | department_id |\n| ----------- | ------------- |\n| 1           | 1             |\n| 2           | 1             |\n| 3           | 3             |\n| 4           | 3             |\n\n#### :zap:[1978. Employees Whose Manager Left the Company](https://leetcode.com/problems/employees-whose-manager-left-the-company/)\nWrite an SQL query to report the IDs of the employees whose salary is strictly less than `$30000` and whose manager left the company. When a manager leaves the company, their information is deleted from the `Employees` table, but the reports still have their `manager_id` set to the manager that left.\n\nReturn the result table ordered by `employee_id`. \n \n```sql\nSELECT employee_id\nFROM Employees\nWHERE salary \u003c 30000 AND manager_id NOT IN (SELECT employee_id FROM Employees)\nORDER BY employee_id;\n```\n                    \n**Output:**\n| employee_id |\n| ----------- |\n| 11          |    \n      \n#### :zap:[1731. The Number of Employees Which Report to Each Employee](https://leetcode.com/problems/the-number-of-employees-which-report-to-each-employee/)\n\nFor this problem, we will consider a **manager** an employee who has at least 1 other employee reporting to them.\n\nWrite an SQL query to report the ids and the names of all managers, the number of employees who report **directly** to them, and the average age of the reports rounded to the nearest integer.\n\nReturn the result table ordered by `employee_id`.         \n\n```sql\nWITH CTE_manager AS (\n    \n    SELECT e1.employee_id, e1.name, COUNT(e2.reports_to) AS reports_count, \n           CEILING(AVG(CONVERT(decimal(7,2),e2.age))) AS average_age\n    FROM Employees AS e1, Employees AS e2\n    WHERE e1.employee_id = e2.reports_to\n    GROUP BY e1.employee_id, e1.name\n)\n\nSELECT *\nFROM CTE_manager\nWHERE reports_count \u003e 0\nORDER BY employee_id;\n```\n\n**Output:**\n| employee_id | name  | reports_count | average_age |\n| ----------- | ----- | ------------- | ----------- |\n| 9           | Hercy | 2             | 39          |\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n     \u003csummary\u003e:orange_circle:Level: Medium\u003c/summary\u003e\n     \n## Solved: \n#### :zap:[176. Second Highest Salary](https://leetcode.com/problems/second-highest-salary/)\nWrite an SQL query to report the second highest salary from the ```Employee``` table. If there is no second highest salary, the query should report ```null```.\n```sql\nSELECT MAX(salary) AS SecondHighestSalary\nFROM Employee\nWHERE salary != (SELECT MAX(salary) FROM Employee);\n```\n**Output:**\n| SecondHighestSalary |\n| ------------------- |\n| 200                 |\n\n#### :zap:[608. Tree Node](https://leetcode.com/problems/tree-node/?envType=study-plan\u0026id=sql-i)\nEach node in the tree can be one of three types:\n\n- **\"Leaf\"**: if the node is a leaf node.\n- **\"Root\"**: if the node is the root of the tree.\n- **\"Inner\"**: If the node is neither a leaf node nor a root node.\n\nWrite an SQL query to report the type of each node in the tree.\n\n```sql\nSELECT id, \nCASE \n    WHEN p_id IS NULL THEN 'Root'\n    WHEN id IN (SELECT p_id FROM Tree WHERE p_id IS NOT NULL) THEN 'Inner'\n    ELSE 'Leaf'\nEND AS type\nFROM Tree;\n```\n\n**Output:**\n| id | type  |\n| -- | ----- |\n| 1  | Root  |\n| 2  | Inner |\n| 3  | Leaf  |\n| 4  | Leaf  |\n| 5  | Leaf  |\n\n#### :zap:[180. Consecutive Numbers](https://leetcode.com/problems/consecutive-numbers/)\n\nWrite an SQL query to find all numbers that appear at least three times consecutively.\n\n```sql\nWITH CTE_logDetails AS (\n    SELECT id, LAG(num) OVER (ORDER BY id) AS PrevNum\n            ,num AS CurrentNum\n            ,LEAD(num) OVER (ORDER BY id) AS NextNum\n    FROM Logs\n)\n\nSELECT DISTINCT CurrentNum AS ConsecutiveNums\nFROM CTE_logDetails\nWHERE PrevNum = CurrentNum AND CurrentNum = NextNum;\n```\n**Output:**\n| ConsecutiveNums |\n| --------------- |\n| 1               |\n\n#### :zap:[1158. Market Analysis I](https://leetcode.com/problems/market-analysis-i/)\n\nWrite an SQL query to find for each user, the join date and the number of orders they made as a buyer in `2019`.\n\n```sql\nSELECT\n    u.user_id AS buyer_id,\n    u.join_date,\n    COUNT(CASE WHEN YEAR(o.order_date) = 2019 THEN 1 ELSE NULL END) AS orders_in_2019\nFROM\n    Users AS u\n    LEFT JOIN Orders AS o ON u.user_id = o.buyer_id\nGROUP BY\n    u.user_id,\n    u.join_date\nORDER BY\n    u.user_id;\n```\n**Output:**\n\n| order_id | order_date | item_id | buyer_id | seller_id |\n| -------- | ---------- | ------- | -------- | --------- |\n| 1        | 2019-08-01 | 4       | 1        | 2         |\n| 2        | 2018-08-02 | 2       | 1        | 3         |\n| 3        | 2019-08-03 | 3       | 2        | 3         |\n| 4        | 2018-08-04 | 1       | 4        | 2         |\n| 5        | 2018-08-04 | 1       | 3        | 4         |\n| 6        | 2019-08-05 | 2       | 2        | 4         |\n\n#### :zap:[1393. Capital Gain/Loss](https://leetcode.com/problems/capital-gainloss/)\n\nWrite an SQL query to report the **Capital gain/loss** for each stock.\n\nThe **Capital gain/loss** of a stock is the total gain or loss after buying and selling the stock one or many times.\n\n```sql\nWITH CTE_stock AS (\n    SELECT stock_name,\n          CASE WHEN operation = 'Buy' THEN price END AS Buy,\n          CASE WHEN operation = 'Sell' THEN price END AS Sell\n    FROM Stocks\n    \n)\n\nSELECT stock_name, (SUM(Sell) - SUM(Buy)) AS capital_gain_loss\nFROM CTE_stock\nGROUP BY stock_name;\n```\n\n**Output:**\n| stock_name   | capital_gain_loss |\n| ------------ | ----------------- |\n| Corona Masks | 9500              |\n| Handbags     | -23000            |\n| Leetcode     | 8000              |\n\n\n#### :zap:[570. Managers with at Least 5 Direct Reports](https://leetcode.com/problems/managers-with-at-least-5-direct-reports/)\n    \nWrite an SQL query to report the managers with at least **five direct reports**.\n```sql\nSELECT name\nFROM employee\nWHERE id IN (\n              SELECT managerId FROM Employee\n              GROUP BY managerId\n              HAVING COUNT(managerID) \u003e= 5)\n```\n**Output:**\n     \n     \n| name |\n| ---- |\n| John |     \n\n     \n#### :zap:[550. Game Play Analysis IV](https://leetcode.com/problems/game-play-analysis-iv/description/)\nWrite an SQL query to report the **fraction** of players that logged in again on the day after the day they first logged in, **rounded to 2 decimal places**. In other words, you need to count the number of players that logged in for at least two consecutive days starting from their first login date, then divide that number by the total number of players.\n\n```sql\nWITH CTE_date AS (\n      SELECT player_id, MIN(event_date) AS start_date\n      FROM Activity\n      GROUP BY player_id\n)\n\nSELECT ROUND(COUNT(DISTINCT c.player_id) / CONVERT(DECIMAL(7,2), (SELECT COUNT(DISTINCT player_id) FROM Activity)), 2) AS fraction\nFROM CTE_date AS c\nJOIN Activity AS a\nON c.player_id = a.player_id\nAND DATEDIFF(day, c.start_date,a.event_date) = 1\n```\n\n**Output:**\n\n| fraction |\n| -------- |\n| 0.33     |\n\n#### :zap:[585. Investments in 2016](https://leetcode.com/problems/investments-in-2016/description/)\nWrite an SQL query to report the sum of all total investment values in 2016 `tiv_2016`, for all policyholders who:\n\n - have the same `tiv_2015` value as one or more other policyholders, and\n - are not located in the same city like any other policyholder (i.e., the `(lat, lon)` attribute pairs must be unique).\n     \nRound `tiv_2016` to **two decimal places**.\n\n```sql\nSELECT ROUND(SUM(tiv_2016),2) AS tiv_2016\nFROM Insurance\nWHERE tiv_2015 IN (\n                  SELECT tiv_2015\n                  FROM Insurance\n                  GROUP BY tiv_2015\n                  HAVING COUNT(tiv_2015) \u003e 1)\nAND CONCAT(lat, lon) IN (\n                  SELECT CONCAT(lat, lon)\n                  FROM Insurance\n                  GROUP BY lat, lon\n                  HAVING COUNT(*) = 1);\n```\n     \n     \n**Output:**\n     \n| tiv_2016 |\n| -------- |\n| 45       |\n     \n#### :zap:[602. Friend Requests II: Who Has the Most Friends](https://leetcode.com/problems/friend-requests-ii-who-has-the-most-friends/description/)\n\nWrite an SQL query to find the people who have the most friends and the most friends number.\n\nThe test cases are generated so that only one person has the most friends.\n\n```sql\nWITH CTE_friendsNr AS (\n          SELECT requester_id, COUNT(*) AS nr_of_friends\n          FROM RequestAccepted\n          GROUP BY requester_id\n          UNION ALL\n          SELECT accepter_id, COUNT(*) AS nr_of_friends\n          FROM RequestAccepted\n          GROUP BY accepter_id)\n\nSELECT TOP 1 requester_id AS id, SUM(nr_of_friends) AS num\nFROM CTE_friendsNr\nGROUP BY requester_id\nORDER BY SUM(nr_of_friends) DESC;\n```\n\n**Output:**\n| id | num |\n| -- | --- |\n| 3  | 3   |\n\n\n#### :zap:[626. Exchange Seats](https://leetcode.com/problems/exchange-seats/)\n\nWrite an SQL query to swap the seat id of every two consecutive students. If the number of students is odd, the id of the last student is not swapped.\n\nReturn the result table ordered by `id` **in ascending order**.     \n     \n```sql\nSELECT (CASE WHEN id % 2 != 0 AND id = counts THEN id\n             WHEN id % 2 != 0 AND id != counts THEN id + 1\n             ELSE id - 1\n        END) as id, student\nFROM seat, (SELECT count(*) as counts FROM seat) as count_seats\nORDER BY id;\n```\n     \n**Input:**                                         \n| id | student |                                 \n| -- | ------- |                                  \n| 1  | Abbot   |                                  \n| 2  | Doris   |                                  \n| 3  | Emerson |                                  \n| 4  | Green   |                                  \n| 5  | Jeames  |                                  \n     \n **Output:**\n| id | student |\n| -- | ------- |\n| 1  | Doris   | \n| 2  | Abbot   |\n| 3  | Green   |\n| 4  | Emerson |\n| 5  | Jeames  |       \n                                                           \n#### :zap:[1045. Customers Who Bought All Products](https://leetcode.com/problems/customers-who-bought-all-products/description/)\n\nWrite an SQL query to report the customer ids from the `Customer` table that bought all the products in the `Product` table.\n\nReturn the result table in **any order**.\n\n```sql\nSELECT c.customer_id\nFROM Product AS p\ninner JOIN (\n            SELECT DISTINCT *\n            FROM Customer\n) AS c\nON p.product_key = c.product_key\nGROUP BY c.customer_id\nHAVING COUNT(p.product_key) = (SELECT COUNT(product_key) FROM Product)\n```\n\n **Output:**\n| customer_id |\n| ----------- |\n| 1           |\n| 3           |    \n     \n\n#### :zap:[1070. Product Sales Analysis III](https://leetcode.com/problems/product-sales-analysis-iii/description/)\n     \nWrite an SQL query that selects the **product id, year, quantity**, and **price** for the **first year** of every product sold.     \n\n```sql      \nWITH CTE_firstYear AS (\n                        SELECT product_id, MIN (year) AS first_year\n                        FROM Sales\n                        GROUP BY product_id)\n\nSELECT first.product_id, first.first_year, s.quantity, s.price\nFROM CTE_firstYear AS first\nINNER JOIN Sales AS S\nON first.product_id = s.product_id\nWHERE s.year = first.first_year;\n```\n     \n**Output:**\n     \n| product_id | first_year | quantity | price |\n| ---------- | ---------- | -------- | ----- |\n| 100        | 2008       | 10       | 5000  |\n| 200        | 2011       | 15       | 9000  |     \n     \n     \n #### :zap:[178.Rank Scores](https://leetcode.com/problems/rank-scores/description/)  \n\n Write a solution to find the rank of the scores. The ranking should be calculated according to the following rules:\n\n- The scores should be ranked from the highest to the lowest.\n- If there is a tie between two scores, both should have the same ranking.\n- After a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no holes between ranks.\nReturn the result table ordered by score in descending order.\n\n```sql\nSELECT score, DENSE_RANK() OVER(ORDER BY score DESC) as rank\nfrom Scores\n```\n\n**Output:**   \n| score | rank |\n| ----- | ---- |\n| 4     | 1    |\n| 4     | 1    |\n| 3.85  | 2    |\n| 3.65  | 3    |\n| 3.65  | 3    |\n| 3.5   | 4    |\n     \n\n#### :zap:[180.Consecutive Numbers](https://leetcode.com/problems/consecutive-numbers/)\n\nFind all numbers that appear at least three times consecutively.\n\nReturn the result table in **any order**.\n\nThe result format is in the following example.\n\n```sql\nSELECT distinct \n    i3.num as ConsecutiveNums\nFROM \n    logs i1,\n    logs i2,\n    logs i3\nWHERE \n    i1.id=i2.id+1 AND \n    i2.id=i3.id+1 AND \n    i1.num=i2.num AND \n    i2.num=i3.num\n```\n**Input:**\n| id | num |\n| -- | --- |\n| 1  | 1   |\n| 2  | 1   |\n| 3  | 1   |\n| 4  | 2   |\n| 5  | 1   |\n| 6  | 2   |\n| 7  | 2   |\n\n**Output:**  \n| ConsecutiveNums |\n| --------------- |\n| 1               |\n\n     \n\u003c/details\u003e\n\n \n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkleamertiri%2Fleetcode-sql-questions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkleamertiri%2Fleetcode-sql-questions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkleamertiri%2Fleetcode-sql-questions/lists"}