PostgreSQL
 sql >> Baza danych >  >> RDS >> PostgreSQL

Czy możliwe jest zliczanie według różnych warunków w jednym zapytaniu?

Aby to osiągnąć, potrzebujesz zapytania przestawnego:

SELECT SUM(CASE WHEN EXTRACT(MONTH FROM dateshipped)::int = 1  THEN 1 ELSE 0 END) AS Jan,
       SUM(CASE WHEN EXTRACT(MONTH FROM dateshipped)::int = 2  THEN 1 ELSE 0 END) AS Feb,
       SUM(CASE WHEN EXTRACT(MONTH FROM dateshipped)::int = 3  THEN 1 ELSE 0 END) AS Mar,
       SUM(CASE WHEN EXTRACT(MONTH FROM dateshipped)::int = 4  THEN 1 ELSE 0 END) AS Apr,
       SUM(CASE WHEN EXTRACT(MONTH FROM dateshipped)::int = 5  THEN 1 ELSE 0 END) AS May,
       SUM(CASE WHEN EXTRACT(MONTH FROM dateshipped)::int = 6  THEN 1 ELSE 0 END) AS Jun,
       SUM(CASE WHEN EXTRACT(MONTH FROM dateshipped)::int = 7  THEN 1 ELSE 0 END) AS Jul,
       SUM(CASE WHEN EXTRACT(MONTH FROM dateshipped)::int = 8  THEN 1 ELSE 0 END) AS Aug,
       SUM(CASE WHEN EXTRACT(MONTH FROM dateshipped)::int = 9  THEN 1 ELSE 0 END) AS Sep,
       SUM(CASE WHEN EXTRACT(MONTH FROM dateshipped)::int = 10 THEN 1 ELSE 0 END) AS Oct,
       SUM(CASE WHEN EXTRACT(MONTH FROM dateshipped)::int = 11 THEN 1 ELSE 0 END) AS Nov,
       SUM(CASE WHEN EXTRACT(MONTH FROM dateshipped)::int = 12 THEN 1 ELSE 0 END) AS Dec
FROM Shipments
WHERE EXTRACT(YEAR FROM dateshipped)::int=2016


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Jak Now() działa w PostgreSQL

  2. PostgreSQL - zapytanie ze skryptu bash jako użytkownik bazy danych 'postgres'

  3. Heroku - ActionView::Template::Error (PG::Error:ERROR:kolumna category_products.desc nie istnieje

  4. Jak używać funkcji okna SQL do obliczania procentu agregatu

  5. Jak zresetować sekwencję dla identyfikatorów w tabelach PostgreSQL