sql >> データベース >  >> RDS >> PostgreSQL

1つのクエリで異なる条件でカウントすることは可能ですか?

    これを実現するには、ピボットクエリが必要です:

    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. MySQLテーブルでは列の順序は重要ですか?

    2. CDbConnectionはDB接続を開くことができませんでした:Yiiでドライバーが見つかりませんでした

    3. 整合性制約違反:1048列'user_id'をnullにすることはできませんロールの割り当て時にエラーが発生します(Laravel 5.3)

    4. ElasticSearchでユーザーの検索クエリを保存する最良の方法は?