Get count(*) inside SELECT
Posted by:
John Noble
Date: October 02, 2020 05:11AM
Hi folks,
I have a datatable with following fields...
customerID, NOTR, invNum, value
Data is
ABC1234, 10, 1, 100
ABC1234, 10, 1, 200
ABC1234, 10, 2, 100
ABC1234, 10, 2, 300
ABC1234, 10, 2, 400
ABC1234, 16, 3, 150
NOTR is nature of transaction. 10 = Invoice, 16 = Credit
I need write a SELECT statement to produce the following
customerID, invCount, invValue, creditCount, creditValue
ABC1234, 2, 700, 1, 150
Where ABC1234 is the customerID,
2 is the DISTINCT number of invNums WHERE notr = 10
700 is the sum of value WHERE notr = 10
1 is the DISTINCT number of invNums WHERE notr = 16
150 is the sum of value WHERE notr = 16
I can manage to get the sums of [value] correct but I don't know how to get the Distinct number of invnums (the 2 and the 1) into the SQL
Here is my sql so far...
SELECT t1.customerID,
SUM(Case WHEN notr = "10" THEN t1.value Else 0 End) invoiceValue,
SUM(Case WHEN notr = "16" THEN t1.value Else 0 End) creditValue
FROM table t1
GROUP BY customerID
I need to get the InvCount (2) and CreditCount (1) into the mysql statement.
Any ideas ??
John