【问题标题】:Cannot figure out how to write MySQL Query无法弄清楚如何编写 MySQL Query
【发布时间】:2021-11-12 09:17:26
【问题描述】:

我正在尝试编写一个 MySQL 选择语句,它将使用 table1table2 生成一个 table3

表1

id Month Year Name Length Breath
1 January 2002 Square 5 2
2 February 2003 Circle 6 3
3 March 2004 Cylinder 7 4
4 April 2005 Cube 8 5
5 May 2006 Quadilateral 9 6

表2

id Month Year Name Frequency Area Volume
1 January 2002 Square 1 20 50
2 Febrauy 2003 Circle 2 25 55
3 March 2004 Cylinder 3 Null 60
4 April 2005 Cube 4 35 65
5 May 2006 Quadilateral 5 40 Null

table3生成的表应该是这样的。

Name Type Month Year Length Breath Frequency Volume/Area Cum_Area Cum_Volume Area Volume
Square 2d January 2002 5 2 1 2.5 20 50 20 50
Circle 2d February 2003 6 3 2 2.2 45 105 25 55
Cylinder 3d March 2004 7 4 3 2 45 165 30 60
Cube 3d April 2005 8 5 4 1.86 80 230 35 65
Quadilateral 4d May 2006 9 6 5 1.75 120 230 40 70

在我尝试过的语句中,每当累积列遇到第一个空值时,从那时起的每一行都是空的。

另外,我如何写类型列?我希望方形和圆形是“2d”;立方体和圆柱体为“3d”,四边形为“4d”。

表 1 和表 2 具有共同的名称、月份和年份列。

【问题讨论】:

  • 使用它们共有的列连接两个表。对Type 列使用CASE 表达式。
  • 类型的条件是什么?你的逻辑是什么?请阅读教程,stackoverflow.com/help/how-to-askmeta.stackoverflow.com/questions/333952/…
  • 为什么是四边形4d?在几何学中,四边形是具有 4 条边的二维形状。
  • 这只是虚拟数据和数字,因为我无法分享真实数据而且它太大了。

标签: mysql


【解决方案1】:

我没有完全理解您的逻辑是什么,或者为什么您在第二张桌子上没有 id。但假设你写的是什么,这是一个建议。
更新您的问题我很乐意更新我的答案。

假设 null 表示 0:

SELECT
table1.Name,
CASE table1.Name 
WHEN Square THEN '2d'
WHEN Circle THEN '2d'
WHEN Cylinder THEN '3d'
WHEN Cube THEN '3d'
WHEN Quadilateral THEN '4d'
END as Type,
table1.Month,
table1.Year,
table1.Length,
table1.Breath,
table2.Frequency,
(IFNULL(table2.Volume,0) / IFNULL(table2.Area,0)) as 'Volume/Area',
//I don't understand what do you need in this field,
//I don't understand what do you need in this field,
table2.Area,
table2.Volume
FROM table1 
JOIN table2
ON table1.Name = table2.Name AND table1.Month = table2.Month AND table1.Year = table2.Year

【讨论】:

  • 感谢您的回答。您省略了我需要的两个字段是面积和体积列的累积添加。有点像两者的总和。这实际上是问题的一部分,它给我带来了最大的麻烦并提示了这个问题。
  • @danielajj 好的,没问题。让我理解,以便我可以编辑我的答案。让我们尝试一下 Circle 的例子。您在 Cum_Volume 中得到 105,因为您(例如)在 table2 中使用 Circle 有三条记录:一条为 55,一条为 20,另一条为 30?
  • 对不起,我有一个关于这个问题的后续问题。我希望按“类型”对生成的表进行排序。所以我将 order by 语句添加到第一个表中。但是一些不遵循 ORDER BY 子句的行位于生成的表的顶部。
猜你喜欢
  • 2017-09-27
  • 2012-03-14
  • 1970-01-01
  • 2014-12-18
  • 1970-01-01
  • 2016-05-04
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多