简体   繁体   中英

Combining aggregate functions across tables in one query

I am trying to build a report using SQL that will return values from completely separate tables in the same query.

I've created three queries that give me each output that I desire, but not able to get these merged into one query to generate a single report.

-- Selects count of new subscriptions from a period and their current status --

SELECT
    COUNT(
        CASE WHEN created >= '2019-05-01'
            AND created <= '2019-05-31' THEN
            1
        END) AS "number of new subscriptions",
    COUNT(
        CASE WHEN status = 'canceled'
            AND created >= '2019-05-01'
            AND created <= '2019-05-31' THEN
            1
        END) AS "count of canceled",
    COUNT(
        CASE WHEN status = 'active'
            AND created >= '2019-05-01'
            AND created <= '2019-05-31' THEN
            1
        END) AS "count of still active",
    COUNT(
        CASE WHEN status = 'trialing'
            AND created >= '2019-05-01'
            AND created <= '2019-05-31' THEN
            1
        END) AS "count of trialing",
    COUNT(
        CASE WHEN status = 'past_due'
            AND created >= '2019-05-01'
            AND created <= '2019-05-31' THEN
            1
        END) AS "count of past due"
FROM
    subscriptions;

-- Total Number of Refunds --

SELECT
        COUNT(
            CASE WHEN received_at >= '2019-05-01'
                AND received_at <= '2019-05-31'
                AND refunded = TRUE THEN
                1
            END) AS "number of refunds"
FROM
    charges;

-- Total Amount Refunded --

SELECT
    ROUND((SUM(amount_refunded) / 100), 2) AS "Total Amount Refunded"
FROM
    charges
WHERE
    received_at >= '2019-05-01'
    AND received_at <= '2019-05-31'
    AND refunded = TRUE;

I would expect the output to be the results of all individual queries merged into one output.

In your case you can cross join derived tables made up from your SELECT s.

SELECT *
       FROM (SELECT <rest of your first query here>) a
            CROSS JOIN (SELECT <rest of your second query here>) b
            CROSS JOIN (SELECT <rest of your third query here>) c;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM