Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL Selecting & Counting From Another Table

I have this query that works excellently and gives me the results I want, however, does anybody know how I can remove any rows that have 0 orders? I am sure it is something simple, I just can’t get my head around it.

In other words, should it only show the top 2 rows?

SELECT customers.id, customers.companyname, customers.orgtype,
   (SELECT COALESCE(SUM(invoicetotal), 0)
    FROM invoice_summary
    WHERE invoice_summary.cid = customers.ID 
    and invoice_summary.submitted between '2022-08-01' and '2022-08-31'
    ) AS total,
    (SELECT COUNT(invoicenumber)
    FROM invoice_summary
    WHERE invoice_summary.cid = customers.ID 
    and invoice_summary.submitted between '2022-08-01' and '2022-08-31'
    ) AS orders
FROM customers WHERE customers.orgtype = 10
 ORDER BY total DESC
ID Company Org Total Orders
1232 ACME 1 10 523.36 3
6554 ACME 2 10 411.03 2
1220 ACME 3 10 0.00 0
4334 ACME 4 10 0.00 0

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use a CTE to keep the request simple :

WITH CTE_Orders AS (        
SELECT customers.id, customers.companyname, customers.orgtype,
       (SELECT COALESCE(SUM(invoicetotal), 0)
        FROM invoice_summary
        WHERE invoice_summary.cid = customers.ID 
        and invoice_summary.submitted between '2022-08-01' and '2022-08-31'
        ) AS total,
        (SELECT COUNT(invoicenumber)
        FROM invoice_summary
        WHERE invoice_summary.cid = customers.ID 
        and invoice_summary.submitted between '2022-08-01' and '2022-08-31'
        ) AS orders
    FROM customers WHERE customers.orgtype = 10
     ORDER BY total DESC
)
SELECT * FROM CTE_Orders WHERE orders > 0

You will find aditionals informations about CTE on Microsoft documentation : https://learn.microsoft.com/fr-fr/sql/t-sql/queries/with-common-table-expression-transact-sql?view=sql-server-ver16

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading