admin

给定正方形网格坐标,如何从该范围内的另一个表中计算数据?

sql

我的表格 网格中 有一堆坐标,它们具有以下模式 ID,x1,x2,y1,y2, 如下所示:

22,910000,920000,120000,130000
67,930000,940000,170000,180000
171,980000,990000,210000,220000

网格 表还为每个坐标元组都有一个ID。

在一个单独的表 崩溃中, 我获得了有关汽车撞车的信息,其中最后两个值分别是“ x_coordinate ”和“ y_coordinate
”。

2007,2,9,4,1,1028977,202232
2004,1,1,1,4,1012600,214101
2003,1,9,1,1,958775,156149
1999,1,1,1,1,997349,175503

1-如何计算每个正方形网格的崩溃次数?(显示2列:网格ID和与之关联的崩溃次数)

2-如果走了另一个方向,我将如何检索在接下来的2005年,2006年和2007年发生了60次以上崩溃的所有“正方形网格”(x1,x2,y1,y2的元组)?
(在HTML中,它看起来像一个包含3列的表格:2005 | 2006 | 2007,并且每年下-协调满足> =
60次车祸标准的元组x1,x2,y1,y2。


阅读 155

收藏
2021-07-01

共1个答案

admin

#1很容易:(这本来是“我应该如何计算哪些交通事故落入网格表中x1,x2,y1,y2坐标的方形网格中?”)

SELECT  DISTINCT
            grid.ID
FROM        crashes
INNER JOIN  grid    
            ON  crashes.x_coordinate BETWEEN grid.x1 AND grid.x2
            And crashes.y_coordinate BETWEEN grid.y1 AND grid.y2

#2只是有点难:(这最初是“在接下来的几年中,我将如何检索崩溃次数超过60的所有“方格”(x1,x2,y1,y2的元组…?”))

SELECT  
            grid.ID, COUNT(*) AS CrashCount
FROM        crashes
INNER JOIN  grid    
            ON  crashes.x_coordinate BETWEEN grid.x1 AND grid.x2
            And crashes.y_coordinate BETWEEN grid.y1 AND grid.y2
WHERE       crashes.yearCol IN(2005, 2006, 2007)
GROUP BY    grid.ID
HAVING      COUNT(*) >= 60

修订后的问题的解决方案…

对于#1“如何计算每个方形网格的崩溃次数?”,这只是对原始#2的简化:

SELECT  
            grid.ID, COUNT(*) AS CrashCount
FROM        crashes
INNER JOIN  grid    
            ON  crashes.x_coordinate BETWEEN grid.x1 AND grid.x2
            And crashes.y_coordinate BETWEEN grid.y1 AND grid.y2
WHERE       crashes.yearCol IN(2005, 2006, 2007)
GROUP BY    grid.ID

对于#2,“在接下来的几年( 每年
):2005、2006和2007年,我将如何检索崩溃次数超过60的所有’方格’(x1,x2,y1,y2的元组)?

SELECT *
FROM
(
    SELECT  grid.ID,
            grid.x1, grid.x2, grid.y1, grid.y2,
            (   SELECT  COUNT(*)
                FROM    crashes
                WHERE   yearCol = 2005
                  And   crashes.x_coordinate BETWEEN grid.x1 AND grid.x2
                  And   crashes.y_coordinate BETWEEN grid.y1 AND grid.y2
            )   As year05,
            (   SELECT  COUNT(*)
                FROM    crashes
                WHERE   yearCol = 2006
                  And   crashes.x_coordinate BETWEEN grid.x1 AND grid.x2
                  And   crashes.y_coordinate BETWEEN grid.y1 AND grid.y2
            )   As year06,
            (   SELECT  COUNT(*)
                FROM    crashes
                WHERE   yearCol = 2007
                  And   crashes.x_coordinate BETWEEN grid.x1 AND grid.x2
                  And   crashes.y_coordinate BETWEEN grid.y1 AND grid.y2
            )   As year07,
    FROM    grid
) As gridSum
WHERE   year05  >= 60
  And   year06  >= 60
  And   year07  >= 60

在TSQL中,我们可以使用WITH子句来简化此操作。

2021-07-01