Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9245559
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T09:17:35+00:00 2026-06-18T09:17:35+00:00

I have a query that I use to generate the total order amount for

  • 0

I have a query that I use to generate the total order amount for customers and group them into columns by month alongside another column that represents total order amount.

Here’s the schema:

temp=# \d+ customers;
                          Table "pg_temp_2.customers"
   Column   |            Type             | Modifiers | Storage  | Description 
------------+-----------------------------+-----------+----------+-------------
 id         | integer                     | not null  | plain    | 
 created_at | timestamp without time zone |           | plain    | 
 name       | text                        |           | extended | 
Indexes:
    "customers_pkey" PRIMARY KEY, btree (id)
Referenced by:
    TABLE "orders" CONSTRAINT "orders_customer_id_fkey" FOREIGN KEY (customer_id) REFERENCES customers(id)
Has OIDs: no


                             Table "pg_temp_2.orders"
   Column    |            Type             |   Modifiers   | Storage | Description 
-------------+-----------------------------+---------------+---------+-------------
 id          | integer                     | not null      | plain   | 
 created_at  | timestamp without time zone | default now() | plain   | 
 customer_id | integer                     |               | plain   | 
 amount      | integer                     |               | plain   | 
Indexes:
    "orders_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "orders_customer_id_fkey" FOREIGN KEY (customer_id) REFERENCES customers(id)
Has OIDs: no

For convenience, I’ve added the create table statements:

create temporary table customers ( id integer primary key, created_at timestamp without time zone, name text); 

create temporary table orders ( id integer primary key, created_at timestamp without time zone, customer_id integer references customers(id));

Here’s the query I’m using:

SELECT
  c.name,
  sum(o.amount),
  CAST(SUM(
   CASE
        WHEN date_trunc('month', o.created_at) BETWEEN '2012-10-01' AND ('2012-11-01'::date - '1 day'::interval)
        THEN o.amount
        ELSE 0
   END
   ) / 100.0 AS MONEY) october2012,
   CAST(SUM(
   CASE
        WHEN date_trunc('month', o.created_at) BETWEEN '2012-11-01' AND ('2012-12-01'::date - '1 day'::interval)
        THEN o.amount
        ELSE 0
   END
   ) / 100.0 AS MONEY) as november2012
FROM orders o
INNER JOIN customers c ON o.customer_id = c.id
WHERE o.created_at >= '01 October 2012'
  AND o.created_At < '01 December 2012'
GROUP BY
 c.name
ORDER BY
  october2012 desc;

How can I get rid of that ugly case statement? There MUST be a more elegant way that rolls up these queries over a certain time slice. I tried to use window functions, but I’ve failed miserably. Any assistance would be appreciated!

I’m using postgresql 9.1

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T09:17:36+00:00Added an answer on June 18, 2026 at 9:17 am

    This is not simpler but is more scalable:

    select *
    from crosstab($$
        with orders as (
            select
                customer_id,
                date_trunc('month', created_at) created_at,
                cast(amount / 100.0 as money) amount
            from orders
            where
                created_at >= '2012-10-01'
                and created_at < '2012-12-01'
        ), months as (
            select
                c.name,
                to_char(o.created_at, 'YYYY-MM') created_at,
                sum(o.amount) amount
            from
                orders o
                inner join
                customers c on c.id = o.customer_id
            group by 1, 2
        )
        select name, created_at, amount
        from months
        union all
        select name, 'Total', sum(amount)
        from months
        group by 1, 2
        order by 1, 2
        $$, $$
        select distinct to_char(created_at, 'YYYY-MM')
        from orders
        where
            created_at >= '2012-10-01'
            and created_at < '2012-12-01'
        union select 'Total'
        order by 1
        $$
    ) as (name text, "2012-10" money, "2012-11" money, "Total" money)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a query below that I use to retrieve the records not updated
I have the next query that I run via SQLCMD.EXE use [AxDWH_Central_Reporting] GO EXEC
I have a Maketable query in an Access db that could use an Autonumber
Hi I have a really complicated dynamic query that i want to use to
I have a .cfc on my server that I use to run a query
I have a boost::unordered_multimap< std::vector<int>, float> . The keys that I use to query
I have a query that basically combines tables of actions and selects from them
I have a view that I want to use to generate a payroll report.
I have a PHP MySQL query that inserts some data into a MySQL database
I have a JDBC query that will generate a huge ResultSet which cannot be

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.