Sql-server – how to retrive data from InvoiceNo

aggregatesql server

select  Month(IH.InvoiceDate) as Month, 
    COUNT(ID.InvoiceNo) as Count,
    COUNT(ID.InvoiceNo) as DirectMobile,
    COUNT(ID.InvoiceNo) as Preselling,
    COUNT(ID.PerformaInvoiceNo) as DirectWeb
    from InvoiceDetail ID
INNER JOIN InvoiceHeader IH ON ID.InvoiceNo = IH.InvoiceNo
WHERE IH.IsBackend = 1
GROUP BY Month(IH.InvoiceDate)

I want to ask how to retrieve data from InvoiceNo into two columns and how to give the where clause to complete these conditions.

Count is full count of every type of invoices and i want to get the count of DirectMobile , DirectWeb and Preselling . For get the count of those 3 these are the coditions.

DirectMobile – IsBackend=0

DirectWeb – IsBackend=1 and PerformaInvoiceNo= '' or 0

Preselling – IsBackend = 1 and PerformaInvoiceNo = a varchar value.

Best Answer

Something like this (untested) might be what you're after:

SELECT Month(IH.InvoiceDate) as Month, 
    COUNT(*) as Count,
    SUM(CASE WHEN IH.IsBackend = 0 THEN 1 ELSE 0 END) as DirectMobile,
    SUM(CASE WHEN IH.IsBackend = 1 AND PerformaInvoiceNo <> '' AND PerformaInvoiceNo <> '0' THEN 1 ELSE 0 END) as Preselling,
    SUM(CASE WHEN IH.IsBackend = 1 AND (ID.PerformaInvoiceNo = '' OR ID.PerformaInvoiceNo = '0') THEN 1 ELSE 0 END) as DirectWeb
FROM InvoiceDetail ID
INNER JOIN InvoiceHeader IH USING (InvoiceNo)
GROUP BY Month(IH.InvoiceDate);

This emulates the effect of the filter clause that is available in Postgres. See https://modern-sql.com/feature/filter It's optional in the SQL:2003 standard.