简体   繁体   中英

sql for 3 table query for sales total

I have 3 tables Table A

geographies  
Atlanta
Miami

Table B

geographies stores  month
Atlanta     1       1
Atlanta     2       1
Atlanta     1       2
Miami       2       1
Miami       3       1

table C

Stores  months   Sales
1        1         100
1        2          50
2        1          25
3        1          10

how do i create a report like this

Geography  Month TotalSales
Atlanta     1     xxx
Atlanta     2     xxxx
Miami       1     xxxxx

thanks for the help

This query is for SQL Server, but if you change the escaping characters [] you can run it on every database.

Basically you JOIN all tables with the relevant columns ang GROUP BY montn and geography

 SELECT ta.[geographies],tb.[month], SUM([Sales]) total_amount FROM TableA ta JOIN TableB tb ON ta.[geographies] = tb.[geographies] JOIN TableC tc ON tc.[Stores] = tb.[Stores] AND tb.[month] = tc.[months] GROUP BY ta.[geographies],tb.[month]
 geographies | month | total_amount:---------- | ----: |  -----------: Atlanta |  1 |  125 Atlanta |  2 |  50 Miami |  1 |  35 

db<>fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM