S
S
Someone Nektovich2015-09-28 17:00:37
SQL
Someone Nektovich, 2015-09-28 17:00:37

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: cec834b11b7948289cc56bf0d776715d.PNG
table2 - Outlaynames
10b68a07a45346759e29b9db37c324d8.PNG
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: a423c2ad6fe7425a9a22d83a6e65654e.PNG
2)
SELECT SUM(SmetaOut.cash), SmetaOut.IdCategories
FROM SmetaOut
WHERE ( (month(SmetaOut.date) = month(GETDATE())) and (SmetaOut.cash<>0))
GROUP BY SmetaOut.IdCategories
result: fe112bb861a64dda841dd3815cef74bb.PNG
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

3 answer(s)
N
nozzy, 2015-11-16
@AmiAkari

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

M
Max, 2015-09-28
@MaxDukov

google INNER JOIN

A
Artur Polozov, 2015-09-30
@Noxy

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 question

Ask a Question

731 491 924 answers to any question