如何在 PostgreSQL 中汇总语句?
How to summarize statement in PostgreSQL?
为了获得最终结果,我需要编写大量查询:
SELECT min(x) from table WHERE column1='ab' AND column2='3';
SELECT min(y) from table WHERE column1='ab' AND column2='3';
SELECT max(x) from table WHERE column1='ab' AND column2='3';
SELECT max(y) from table WHERE column1='ab' AND column2='3';
SELECT min(x) from table WHERE column1='ab' AND column2='4';
SELECT min(y) from table WHERE column1='ab' AND column2='4';
SELECT max(x) from table WHERE column1='ab' AND column2='4';
SELECT max(y) from table WHERE column1='ab' AND column2='4';
...
其中 column2
来自 3-8
。
我想我可以 CASE
以某种方式做到这一点,也许可以为 column2
做某种 FOR
循环,但我没有成功。或者我可以用它做其他事情?
想要的结果:
column2 | minx | miny | maxx | maxy |
3 | number | number | number | number |
4 | number | number | number | number |
5 | number | number | number | number |
6 | number | number | number | number |
7 | number | number | number | number |
8 | number | number | number | number |
任何帮助appriciated!
不确定您将如何在其中使用 case,但看起来像是 group by 语句的简单用法。
SELECT Column2, Min(x), Min(y), Max(x), Max(y)
FROM table
WHERE Column1='ab' AND Column2 > 2 AND Column2 < 9 GROUP BY Column2
我通常为 MS-SQL 做 T-SQL,但这是非常基础的,所以我希望它能在 Postgres
上运行
为什么会这样?您可以按 column2 分组。
select
column2,
min(x) as minx,
min(y) as miny,
max(x) as maxx,
max(y) as maxy
from table
where column1 = 'ab' and column2 between 3 and 8
group by
column2
为了获得最终结果,我需要编写大量查询:
SELECT min(x) from table WHERE column1='ab' AND column2='3';
SELECT min(y) from table WHERE column1='ab' AND column2='3';
SELECT max(x) from table WHERE column1='ab' AND column2='3';
SELECT max(y) from table WHERE column1='ab' AND column2='3';
SELECT min(x) from table WHERE column1='ab' AND column2='4';
SELECT min(y) from table WHERE column1='ab' AND column2='4';
SELECT max(x) from table WHERE column1='ab' AND column2='4';
SELECT max(y) from table WHERE column1='ab' AND column2='4';
...
其中 column2
来自 3-8
。
我想我可以 CASE
以某种方式做到这一点,也许可以为 column2
做某种 FOR
循环,但我没有成功。或者我可以用它做其他事情?
想要的结果:
column2 | minx | miny | maxx | maxy |
3 | number | number | number | number |
4 | number | number | number | number |
5 | number | number | number | number |
6 | number | number | number | number |
7 | number | number | number | number |
8 | number | number | number | number |
任何帮助appriciated!
不确定您将如何在其中使用 case,但看起来像是 group by 语句的简单用法。
SELECT Column2, Min(x), Min(y), Max(x), Max(y)
FROM table
WHERE Column1='ab' AND Column2 > 2 AND Column2 < 9 GROUP BY Column2
我通常为 MS-SQL 做 T-SQL,但这是非常基础的,所以我希望它能在 Postgres
上运行为什么会这样?您可以按 column2 分组。
select
column2,
min(x) as minx,
min(y) as miny,
max(x) as maxx,
max(y) as maxy
from table
where column1 = 'ab' and column2 between 3 and 8
group by
column2