Tuesday, December 31, 2024

How do you write a query to compare the total of approved and rejected publications in each year in SQL server?

 To compare the total of approved and rejected publications in each year using SQL Server, you can use a GROUP BY clause to group the records by year and publication status, then use COUNT() to calculate the totals for each status within each year. Assuming you have a table called publications with columns publication_date (or year), and status (with values like 'approved' or 'rejected'), the query would look like this:

SELECT 
    YEAR(publication_date) AS publication_year,
    SUM(CASE WHEN status = 'approved' THEN 1 ELSE 0 END) AS approved_count,
    SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) AS rejected_count
FROM 
    publications
GROUP BY 
    YEAR(publication_date)
ORDER BY 
    publication_year;

Explanation:

  1. YEAR(publication_date): Extracts the year from the publication_date field. If you already have a year column, replace YEAR(publication_date) with year.
  2. CASE WHEN status = 'approved' THEN 1 ELSE 0 END: This condition checks if the status is 'approved'. If true, it returns 1 (otherwise 0), and the SUM() will count how many publications are approved.
  3. CASE WHEN status = 'rejected' THEN 1 ELSE 0 END: Similarly, this condition checks for 'rejected' publications and counts them.
  4. GROUP BY YEAR(publication_date): Groups the results by the publication year.
  5. ORDER BY publication_year: Orders the results by year in ascending order.

Example Output:

publication_year approved_count rejected_count
2020 120 30
2021 110 25
2022 140 40

This query will give you the total count of approved and rejected publications for each year.

No comments:

Post a Comment