I have two tables
type can be only either debit or credit and instrument can be any method like credit card etc.
What I need is to get a query which select year, month,type, instrument and the sum of 'amount' grouped by type and instrument as well as sum of income grouped by year and month.
I can get values using two different queries
example:
to get the sum of income grouped by year and month:
select sum(T.income) as total
from transaction as T, date as D
where D.id = T.id
group by D.month, D.year)
And to get other values:
select D.year, D.month,
T.type, T.instrument, sum(T.amount) as sumAmount,T.income
from date as D, transaction as T
where D.id=T.id,
group by T.instrument, T.type
but I need to get it done by a single query. Is there another way to retrieve this data set? Is it possible to use group by in two ways in the same select statement?
Yes, it is possible to use MySQL GROUP BY clause with multiple columns just as we can use MySQL DISTINCT clause. Consider the following example in which we have used DISTINCT clause in first query and GROUP BY clause in the second query, on 'fname' and 'Lname' columns of the table named 'testing'.
To combine two or more SELECT statements to form a single result table, use the set operators: UNION, EXCEPT or INTERSECT.
SELECT Statement: The GROUP BY Clause in SQLA GROUP BY clause can contain two or more columns—or, in other words, a grouping can consist of two or more columns.
Both GROUP BY and ORDER BY are clauses (or statements) that serve similar functions; that is to sort query results. However, each of these serve very different purposes; so different in fact, that they can be employed separately or together.
Is this the one you are looking for?
SELECT tableA.ID, tableA.`Year`, tableA.`Month`,
tableA.`Type`, tableA.instrument,
tableA.totalAmount, tableB.totalInstrument
FROM
(
SELECT a.ID, a.`Year`, a.`Month`,
b.`Type`, b.instrument,
SUM(b.`amount`) totalAmount
FROM `date` a
INNER JOIN `transactions` b
ON a.ID = b.id
GROUP BY b.`Type
) tableA
INNER JOIN
(
SELECT a.ID, a.`Year`, a.`Month`,
b.`Type`, b.instrument,
SUM(b.`instrument`) totalInstrument
FROM `date` a
INNER JOIN `transactions` b
ON a.ID = b.id
GROUP BY a.`Year`, a.`Month`
) tableB ON tableA.ID = tableB.ID AND
tableA.`Year` = tableB.`Year` AND
tableA.`Month` = tableB.`Month`
the first subquery is by getting the sum of the amount and the second subquery gets the sum of the instrument. their results will be joined in order to get the totalAmount and totalInstrument in a row.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With