2017-10-12 11 views
1

이 I는 표 calcuSQL 열 산출 mininimum 값

id date  name  s1  s2  s3  s4  min_value 
1 10/10/2017 dicky 7  4  8  9  [4] 
2 10/10/2017 acton 12  15  17  19  [15] 
3 10/10/2017 adney 28  13  19  14  [13] 
------------------------------------------------------------------ 
when total by date  47  32  44  42 

여기서 명명 한이 때문에 s2 값 = min_value 열이다.

check sqlfiddle here

지금 아무 문제가 없다. 그러나 s1, s2, s3, s4 값의 필드 중 하나라도 [see below example]과 같으면 min_value 필드가 두 배로되고 모든 열이 두 배가됩니다. 예 :

id date  name  s1  s2  s3  s4  min_value 
1 10/10/2017 dicky 7  24  8  11  [8]/[11] 
2 10/10/2017 acton 12  15  17  19  [17]/[19] 
3 10/10/2017 adney 28  13  19  14  [19]/[14] 
------------------------------------------------------------------ 
when total by date  47  52  44  44 

여기 최소값 열 s3 ANS s4, I가 어느 s3 또는 s4 열이 min_value 컬럼에 충전되는 것을 의미 s3 or s4에서 모든 열을 필요

이다.

see the problem here with sqlfiddle

내가 MySQL을 사용하고 있습니다.

+1

귀하의 질문에 명확 .. – scaisEdge

+0

당신이 **'GROUP BY' ** 결과를, 또는 **'DISTINCT' ** 값을 선택하려고 노력하지 않은 실행 솔루션을 참조하십시오? – AlexCode

+0

1 단계 날짜를 날짜로 저장하십시오. 그럼 우리 한테 돌아와. – Strawberry

답변

2

sqlfiddle을 기반으로 원하는 것을 얻기 위해 중첩 된 쿼리 외부에 GROUP BY를 추가해야합니다.

select c.id, c.date, c.name, c.s1, c.s2, c.s3, c.s4, 
    case v.s 
     when 1 then c.s1 
     when 2 then c.s2 
     when 3 then c.s3 
     when 4 then c.s4 
    end as min_value 
from calcu c 
join (
    select date, s, sum(val) val_sum 
    from (         #unpivot your data 
     select date, s1 as val, 1 as s 
     from calcu 
     union all 
     select date, s2 as val, 2 as s 
     from calcu 
     union all 
     select date, s3 as val, 3 as s 
     from calcu 
     union all 
     select date, s4 as val, 4 as s 
     from calcu 
    ) x 
    group by date, s 
) v on c.date = v.date 
where not exists ( #we are only interested in the minimum val_sum above 
    select 1 
    from (        #note this is the same derived table as above 
     select date, s, sum(val) val_sum 
     from (
      select date, s1 as val, 1 as s 
      from calcu 
      union all 
      select date, s2 as val, 2 as s 
      from calcu 
      union all 
      select date, s3 as val, 3 as s 
      from calcu 
      union all 
      select date, s4 as val, 4 as s 
      from calcu 
     ) x 
     group by date, s 
    ) v2 
    where v2.date = v.date 
    and v2.val_sum < v.val_sum 

) GROUP BY c.id # This is the addition you need 

here