2010-07-08 2 views
0

postresql에서 somwthing을 할 수 있습니까?postregsql에서 하나 이상의 컬럼을 얻는 방법?

select min(column1, column2) as Min, max(column1, column2) as Max from mytable; 
+0

mytable의 각 행에 대해 column1과 column2의 최소값을 원하거나 모든 행에서 단일 값의 최소값을 원합니까? 나는 전자를 추측한다. – Tom

+0

이것은 http://stackoverflow.com/questions/318988/ –

답변

2

옵션 1 :

select CASE when a.min1 < a.min2 then a.min1 else a.min2 END as minimum, 
CASE when a.max1 > a.max2 then a.max1 else a.max2 END as maximum 
from (select min(col1) as min1, min(col2) as min2, max(col1) as max1, 
    max(col2) as max2 from myTable) a 

옵션 2 :

select CASE when MIN(col1) < MIN(col2) THEN MIN(col1) ELSE MIN(col2) END as Minimum, 
    CASE WHEN MAX(col1) > MAX(col2) THEN MAX(col1) ELSE MAX(col2) END as Maximum 
from myTable 

최종 옵션 : 어떻게 이런 일에 대한

select LEAST(MIN(col1),MIN(col2)) as myMinimum, GREATEST(MAX(col1),MAX(col2)) as myMaximum from myTable 

? :)

+0

의 중복으로 보이는 몇 가지 쉬운 방법이 있습니까? – helle

+0

@helle : 두 번째 가능성을 추가했습니다. – Fosco

+0

주 질문에 대한 Tom의 의견에 대한 답변에 따라 수정해야합니다. – Fosco

0
select 
    min(CASE when a.min1 < a.min2 then a.min1 else a.min2 END) as minimum, 
    max(CASE when a.max1 > a.max2 then a.max1 else a.max2 END) as maximum 
from myTable as a 
+1

인덱스를 확인하려면'min()'외부에'case with '를 넣어야합니다. –

+0

인덱스는 어떻게 영향을 줍니까? WHERE 절이 없습니다. – Madhivanan

+0

MIN은 보통 min을 반환하기 위해 인덱스를 사용할 수 있습니다. MIN (column_with_index)을 얻기 위해 SQL에 지시하면. 그러나, postgres에게 MIN (CASE 표현식)을 알려주는 경우 case 표현식이 실제로 index로 덮여있을 수 있다는 사실을 사용할 수없고 각 행에 종속적이지 않다는 사실을 알 수 없다. 실제로는 각 행에 대해 사례를 평가하고 최소값을 추적합니다. 그것을 시도하고 실행 계획을 비교하십시오. – Unreason

3

LEAST (a, b) sql 함수를 사용하려고합니다.

다른 스택 오버플로 질문 How do I get the MIN() of two fields in Postgres?

SELECT LEAST(column1, column2) as Min, 
     GREATEST(column1, column2) as Max 
FROM mytable; 

공식 PostgreSQL의 문서 here입니다에 대답했다.

관련 문제