我在美国有一张MySQL经销商销售表。它包含每个位置的邮寄地址,包括州。我被要求编制一份报告,列出太平洋,山区,西北中部,东北中部,大西洋中部,新英格兰,西南中部,东南中部,南大西洋和AK&等地区的经销商; HI为AK_HI。
报告需要如下所示:
Region State Average_Sales_by_state number_of_distributors
------ ----- ---------------------- ----------------------
Pacific WA $1234 10
OR $4321 20
CA $9876 40
New England ME $1212 15
MA $2222 12
...
我如何在MySQL中处理这个问题,这样当我进行查询以生成报告时,它会以优雅的方式汇集在一起?此外,它需要按Average_Sales_by_state列的降序排序(我在上面的示例中没有这样做)。
我在想我应该创建一个名为US_Regions的新MySQL表,它将具有一个带有region&的记录布局。州,每个州都会有一排。如果我走这条路线,查询会产生什么样的报告,例如上面的报告?谢谢!
这是MySQL US_Regions表:
+----+--------------------+-------+
| id | Region | State |
+----+--------------------+-------+
| 1 | Pacific | WA |
| 2 | Pacific | OR |
| 3 | Pacific | CA |
| 4 | Mountain | MT |
| 5 | Mountain | ID |
| 6 | Mountain | WY |
| 7 | Mountain | NV |
| 8 | Mountain | UT |
| 9 | Mountain | CO |
| 10 | Mountain | AZ |
| 11 | Mountain | NM |
| 12 | West North Central | ND |
| 13 | West North Central | MN |
| 14 | West North Central | SD |
| 15 | West North Central | NE |
| 16 | West North Central | IA |
| 17 | West North Central | KS |
| 18 | West North Central | MO |
| 19 | East North Central | WI |
| 20 | East North Central | IL |
| 21 | East North Central | MI |
| 22 | East North Central | IN |
| 23 | East North Central | OH |
| 24 | Middle Atlantic | PA |
| 25 | Middle Atlantic | NY |
| 26 | Middle Atlantic | CT |
| 27 | Middle Atlantic | NJ |
| 28 | New England | NH |
| 29 | New England | VT |
| 30 | New England | ME |
| 31 | New England | MA |
| 32 | New England | RI |
| 33 | West South Central | OK |
| 34 | West South Central | AR |
| 35 | West South Central | TX |
| 36 | West South Central | LA |
| 37 | East South Central | KY |
| 38 | East South Central | TN |
| 39 | East South Central | MS |
| 40 | East South Central | AL |
| 41 | South Atlantic | WV |
| 42 | South Atlantic | VA |
| 43 | South Atlantic | NC |
| 44 | South Atlantic | SC |
| 45 | South Atlantic | GA |
| 46 | South Atlantic | FL |
| 47 | South Atlantic | DE |
| 48 | South Atlantic | MD |
| 49 | South Atlantic | DC |
| 50 | Alaska-Hawaii | AK |
| 51 | Alaska-Hawaii | HI |
+----+--------------------+-------+
答案 0 :(得分:1)
在你的表格描述中有非常大的猜测,但是这样的(未经测试)。希望这可以让您使用每个州一行的区域表。
SELECT b.Region, a.State, AVG(SaleValue) AS Average_Sales_by_state, COUNT(b.DistributorId)
FROM Sales a
INNER JOIN Distributors b ON a.DistributorId = b.DistributorId
INNER JOIN US_Regions c ON b.State = c.State
GROUP BY b.Region, a.State
ORDER BY b.Region, Average_Sales_by_state DESC