[英]sql for 3 table query for sales total
I have 3 tables Table A我有 3 张桌子表 A
geographies
Atlanta
Miami
Table B表 B
geographies stores month
Atlanta 1 1
Atlanta 2 1
Atlanta 1 2
Miami 2 1
Miami 3 1
table C表 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.此查询适用于 SQL 服务器,但如果您更改 escaping 字符 [],您可以在每个数据库上运行它。
Basically you JOIN
all tables with the relevant columns ang GROUP BY
montn and geography基本上,您将所有表与相关列 ang GROUP BY
JOIN
和 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 | 1 | 125 Atlanta | 125 亚特兰大 | 2 | 2 | 50 Miami | 50 迈阿密 | 1 | 1 | 35 35
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.