Answer the question
In order to leave comments, you need to log in
How to combine a complex SQL query and a selection from several tables?
The program should calculate how much the user spent per month. There are 2 tables. table1 - SmetaOut:
table2 - Outlaynames
Table1 contains:
cash - amount spent
data - date spent
IdCategories - foreign key to table2
Table2 contains:
id - record key
name - category hire
Essence of the question: from these two tables it is necessary to make a selection of non-zero costs for the current month (records with the same external IdCategories are summed). But having summed up, I want to get the corresponding name instead of IdCategories in one request. I only thought of two separate requests.
1)
SELECT OutlayNames.name, SmetaOut.cash
FROM SmetaOut, OutlayNames
WHERE ( (month(SmetaOut.date) = month(GETDATE())) and (SmetaOut.cash<>0) and (OutlayNames.Id=SmetaOut.IdCategories))
resulting in:
2)
SELECT SUM(SmetaOut.cash), SmetaOut.IdCategories
FROM SmetaOut
WHERE ( (month(SmetaOut.date) = month(GETDATE())) and (SmetaOut.cash<>0))
GROUP BY SmetaOut.IdCategories
result:
Question: how to combine them into one?
(to have
taxes 25
food 75)
Sincerely thank you in advance)
Answer the question
In order to leave comments, you need to log in
In your first query, the tables are already connected, you only need to add sum and group by:
SELECT OutlayNames.name, SmetaOut.IdCategories, SUM(SmetaOut.cash)
FROM SmetaOut, OutlayNames
WHERE ( (month(SmetaOut.date) = month(GETDATE())) and (SmetaOut.cash<>0) and (OutlayNames.Id=SmetaOut.IdCategories))
GROUP BY OutlayNames.name, SmetaOut.IdCategories
SELECT O.Id AS IdCategories, O.name, SUM(S.cash) AS Summ
FROM OutlayNames O
LEFT JOIN SmetaOut S ON (O.Id=S.IdCategories)
WHERE ( (month(S.date) = month(GETDATE())) and (S.cash<>0))
GROUP BY O.Id, O.name
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question