Just an example but should work:
SELECT r.cardId AS `Card Number`,
COUNT(*) AS `# of Transactions`,
SUM(t.sales) AS `Total Sales`
FROM transactions t
JOIN (SELECT transactionId, cardId
FROM transactions
WHERE cardId IS NOT NULL OR
cardId != ''
) AS r
ON r.transactionId = t.transactionId
GROUP BY t.transactionId
Basically what I am doing is:
- On the outer select we grab all the results grouped by the
transactionId
this way we can easily count the number of transaction and sum the total of sales. - Then on the join I am basically filtering so we grab the
cardId
from a transaction that does not have it null or empty.
And the result should be what you described.
CARD NUMBER # OF TRANSACTIONS TOTAL SALES
5845 3 141
3957 5 177
For the raw+matching result:
SELECT t.transactionId,
r.cardId,
t.sales
FROM transactions t
JOIN (SELECT transactionId, cardId
FROM transactions
WHERE cardId IS NOT NULL OR
cardId != ''
) AS r
ON r.transactionId = t.transactionId
To update the empty results you could use an UPDATE
like this:
UPDATE transactions t
JOIN (SELECT transactionId, cardId
FROM transactions
WHERE cardId IS NOT NULL OR
cardId != ''
) AS m
ON m.transactionId = t.transactionId
SET t.cardId = m.cardId
WHERE t.cardId IS NULL OR
t.cardId = ''