Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To find users who made at least three purchases in each of April, May, and June 2023, group purchases by user and month, keep months with at least three rows, then group those qualifying months by user and require three. Join the qualifying users back to all purchases in the date window to calculate their total spending.

PostgreSQL solution

This query returns each qualifying user’s email and total purchase amount for the full three-month window. It assumes each user_id has one row in users.

WITH monthly_counts AS (
    SELECT
        user_id,
        date_trunc('month', purchase_date)::date AS purchase_month,
        COUNT(*) AS purchase_count
    FROM purchases
    WHERE purchase_date >= DATE '2023-04-01'
      AND purchase_date <  DATE '2023-07-01'
    GROUP BY user_id, date_trunc('month', purchase_date)::date
    HAVING COUNT(*) >= 3
), power_users AS (
    SELECT user_id
    FROM monthly_counts
    GROUP BY user_id
    HAVING COUNT(*) = 3
)
SELECT
    u.user_id,
    u.email,
    CAST(COALESCE(SUM(p.amount), 0) AS DECIMAL(10, 2)) AS total_amount_spent
FROM power_users pu
JOIN users u ON u.user_id = pu.user_id
JOIN purchases p ON p.user_id = pu.user_id
WHERE p.purchase_date >= DATE '2023-04-01'
  AND p.purchase_date <  DATE '2023-07-01'
GROUP BY u.user_id, u.email
ORDER BY total_amount_spent DESC, u.user_id ASC;

How the two GROUP BY levels work

First level: count purchases per user-month

The first WHERE limits the rows before aggregation to April 1 through June 30, 2023. Grouping on user_id and the month creates one group for each user-month that has purchases. HAVING COUNT(*) >= 3 keeps only months with at least three purchase rows.

COUNT(*) is deliberate: it counts rows even when amount is NULL. COUNT(amount) would ignore those rows and could incorrectly disqualify a user. PostgreSQL documents the order and roles of WHERE, GROUP BY, and HAVING, and distinguishes row counts from non-NULL expression counts in its aggregate-function documentation.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Second level: require all three months

monthly_counts contains only qualifying user-months. The second grouping makes one group per user, and HAVING COUNT(*) = 3 requires exactly three qualifying month rows. Since the date window contains exactly April, May, and June 2023 and the first grouping produces at most one row per user in each month, three rows means the user met the threshold in every target month. A missing month produces no group and therefore cannot pass this test.

Final level: sum the full period

The final query joins qualifying IDs to purchases again and sums every purchase amount in the date window—not only rows retained as qualifying monthly groups. PostgreSQL’s SUM ignores NULL amounts and returns NULL when there are no non-NULL values; COALESCE(..., 0) makes an all-NULL total display as zero. The cast requests two decimal places. Results are ordered by spending from highest to lowest, then by smaller user_id for ties.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Date boundaries and grouping details

Use a half-open interval for timestamps

The range >= DATE '2023-04-01' AND < DATE '2023-07-01' includes all times on June 30 when purchase_date is a timestamp. An upper bound of June 30 at midnight can exclude later transactions that day. For a DATE column, an inclusive upper bound of June 30 would work, but the exclusive next-day boundary is consistent and explicit.

Keep the year in the month key

Grouping only by month number can combine April from different years if the data window later expands. The example truncates the date to a year-and-month value before grouping, so April 2023 remains distinct from April in another year.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Common mistakes and adaptations

  • Applying the threshold to the whole quarter: GROUP BY user_id HAVING COUNT(*) >= 9 does not prove that a user made three purchases in each month; the purchases could be concentrated in one month. The first grouping preserves the monthly condition.
  • Using COUNT(amount): this omits NULL-valued purchase rows, contrary to the stated rule that each purchase row counts.
  • Summing only the filtered monthly groups: the qualifying CTE is for determining who qualifies. The final sum needs the complete date-window rows for those users.
  • Joining duplicate user records: if users has multiple rows for one user_id, the join can multiply purchase rows and inflate the sum. Enforce uniqueness or aggregate purchases before joining.
  • Changing the period: HAVING COUNT(*) = 3 is correct for these three target months. For a different number of required months, update the expected count or explicitly test the required months.
  • Porting to another database: the example uses PostgreSQL’s date_trunc and cast syntax. Month-extraction and date functions differ by SQL dialect; check the target engine’s syntax rather than copying those expressions unchanged.
  • Rounding or numeric types: DECIMAL(10, 2) expresses the requested two-decimal output in PostgreSQL. Confirm the target database’s numeric type and rounding behavior when adapting the query.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.