2017-12-28 28 views
1

나는 sqlite chinook 데이터베이스를 사용하고 있는데,이 시나리오를 보았습니다. db는 invoices 테이블이 연결된 뮤직 스토어를 나타내며 customers에 연결됩니다.sqlite 쿼리에서 상위 그룹을 얻는 방법은 무엇입니까?

Invoices 표는 내가 customers 테이블에서 country에 의해 sum() 그룹화를 사용하여 집계 할 수있는 total 열이 있습니다. 이 같은

SELECT 
    c.country, 
    sum(i.total) totalspent, 
    c.firstname, 
    c.lastname 

FROM 
    invoices i 
    left join customers c on c.customerid= i.customerid 

group by 
    c.country, 
    c.firstname, 
    c.lastname 

order by 2 desc 

이 출력됩니다 뭔가 :

.---------------------------------------------. 
| Country | totalspent | firstname | lastname | 
|----------------------------------------------| 
| Czech R. | 49.62  | Helena | Holy | 
| USA  | 47.62  | Richard | Cunning | 
| Chile | 46.62  | Luis  | Rojas | 
| Hungary | 45.62  | Ladislav | Kovac | 
| Ireland | 45.62  | Hugh  | O'Reilly | 
| USA  | 43.62  | Julia | Barnett | 
... 
... 

당신은 테이블 totalSpent 내림차순으로 정렬됩니다 알 수 있습니다. 이로 인해 동일한 국가 출신의 사람들이 지출 한 금액에 따라 순서가 달라집니다.

각 국가별로 최상위 행을 하나만 가져올 수있는 방법은 무엇입니까? 각 국가별로 그룹화 된 totalselect max()을 시도했지만 작동하지 않았습니다.

select 
    ... 
    ... 
where 
    sum(i.total) in (select max(sm) 
        from (select 
            sum(ii.total) sm 
          from 
            invoices ii left join customers cc 
            on cc.customerid = ii.customerid 
          where cc.country = c.country)) 


... 
group by 
    ... 

하지만 그 또한 작동하지 않았다 : 여기

내가 시도한 것입니다.

결과 행에서 최상위 국가 만 선택하는 것이 더 직접적인 방법이어야합니다.

답변

1

당신은 CTE를 사용할 수 있습니다

with ic as (
     select c.country, sum(i.total) as totalspent, c.firstname, c.lastname 
     from invoices i left join 
      customers c 
      on c.customerid = i.customerid 
     group by c.country, c.firstname, c.lastname 
    ) 
select ic.* 
from ic 
where ic.totalspent = (select max(ic2.totalspent) from ic ic2 where ic2.country = ic.country); 
order by 2 desc 
+0

이 동시에 준비하고 효율적으로 쿼리를 쉽게 유지하면서 내가 원하는 출력을 얻을 필요 정확히이다. – Ahmad

0

SQLite에는 창 기능이 없습니다.

이의이 현재 결과입니다 가정하자 :

는이 시나리오에 대한 솔루션 있는지 확인, 그냥 방법입니다

sqlite> create table c (i int, p varchar(100), c varchar(100)); 
sqlite> insert into c values 
    ...> (100, 'pedro', 'USA'), 
    ...> (120, 'marta', 'Spain'), 
    ...> ( 90, 'juan', 'USA'), 
    ...> (130, 'laura', 'Spain'); 

그런 다음, 쿼리가 될 수 있습니다

sqlite> select c.* 
    ...> from c inner join 
    ...> (select c, max(i) as i from c group by c) m 
    ...> on c.c = m.c and c.i=m.i; 

하위 쿼리에서 각 국가의 최대 값을 얻습니다.

결과 : 당신의 선택에서 선택을 할 수있는 당신이해야 귀하의 경우

100|pedro|USA 
130|laura|Spain 

공지 사항.