[英]SQL: How to build complex query from 3 tables
I have 3 tables with data and I need to select sum of sales (SalesAmount) per country(CountryRegionName) in 2014 fiscal year (FiscalYear). 我有3个数据表,我需要选择2014财政年度(FiscalYear)中每个国家/地区(CountryRegionName)的销售总额(销售额)。
The first table is Geography
. 第一个表格是
Geography
。
There are data with CountryRegionName
and also SalesTerritoryKey
(number which means some districts of CountryRegionName
). 有带有
CountryRegionName
数据以及SalesTerritoryKey
(数字,这表示CountryRegionName
某些地区)。
The second table, anong others, has information about OrderDateKey
, SalesTerritoryKey
and SalesAmount
. 第二个表以及其他一些表具有有关
OrderDateKey
, SalesTerritoryKey
和SalesAmount
。 The OrderDateKey
field include records in the following format: "20130828". OrderDateKey
字段包含以下格式的记录:“ 20130828”。
The third table, among others, has fields DateKey
(in the same format as OrderDateKey
from second table and FiscalYear
(format like: "2012"). 第三个表,除其他外,具有字段
DateKey
(格式与第二个表中的OrderDateKey
和FiscalYear
(格式:“ 2012”)相同)。
I dont't understand how I can select needed data using all 3 tables because second table has information about year ( OrderDateKey
) in different format which third table supports in field FiscalYear
. 我不明白如何使用所有3个表来选择所需的数据,因为第二个表以不同的格式提供了有关
FiscalYear
( OrderDateKey
)的信息,而第三个表在FiscalYear
字段中支持。
Currently I stopped which following statement: 目前,我停止了以下声明:
`SELECT CountryRegionName, SUM(SalesAmount) FROM FirstTable GROUP BY SalesTerritoryKey`
I know that we need to join all tables and make some subqueries but don't understand how to compare dates and countries which are in different formats. 我知道我们需要联接所有表并进行一些子查询,但不了解如何比较日期和采用不同格式的国家/地区。 Thanks for your help!
谢谢你的帮助!
SELECT t1.CountryRegionName, SUM(t2.SalesAmount)
FROM ThirdTable t3
LEFT JOIN SecondTable t2
ON t3.DateKey = t2.OrderDateKey
LEFT JOIN FirstTable t1
ON t1.SalesTerritoryKey = t2.SalesTerritoryKey
WHERE t3.FiscalYear = "2014"
GROUP BY t1.CountryRegionName
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.