2017-07-29 4 views
0

のための最高の数を返す私はsection_mod_idクエリは、各行

この

day_id section_mod_id totalColumns 
----------------------------------- 
127   2    3 
23   6    1 

クエリ

SELECT 
    day_id, section_mod_id, count(day_id) as totalColumns 
FROM 
    `supervision` sup 
INNER JOIN 
    `section_mod` s ON sup.section = s.section_mod_id 
GROUP BY 
    day_id, section_mod_id 
ORDER BY 
    (s.section_mod_id) ASC 

例えば

day_id section_mod_id totalColumns 
----------------------------------- 
127   2    3 
103   2    1 
23   2    2 
105   2    1 
23   6    1 

でグループ化された最高totalColumns番号を取得することができます返品のみ各セクションの最高番号

mysqlデータベースを使用することは可能ですか?

+2

このデータベースを使用していますか? –

+0

私はmysqlを使用しています。 –

答えて

1

は、サブクエリを使用して以下に試してみてください:MySQLで

SELECT sm.* 
FROM (SELECT day_id, section_mod_id, count(*) as totalColumns, 
      ROW_NUMBER() OVER (PARTITION BY section_mod_id ORDER BY count(*) DESC) as seqnum 
     FROM supervision s INNER JOIN 
      section_mod m ON s.section = m.section_mod_id 
     GROUP BY day_id, section_mod_id 
    ) sm 
WHERE seqnum = 1; 

を、最も簡単な方法は、おそらく、このトリックです。

注:内部サブクエリには一時テーブルを使用できます。

select day_id,section_mod_id,totalColumns from 
    (
    select t1.day_id ,t1.section_mod_id,t1.totalColumns 
    ,count(*) as rowNumber 
    from   
     (SELECT day_id, section_mod_id, count(day_id) as totalColumns FROM supervision sup 
      INNER JOIN section_mod s ON sup.section = s.section_mod_id GROUP BY day_id, section_mod_id 
     ) t1 
      inner join 
     (SELECT day_id, section_mod_id, count(day_id) as totalColumns FROM supervision sup 
      INNER JOIN section_mod s ON sup.section = s.section_mod_id GROUP BY day_id, section_mod_id 
     )t2 
     on t1.section_mod_id=t2.section_mod_id 
     and t1.totalColumns<=t2.totalColumns 
    group by t1.day_id, t1.section_mod_id,t1.totalColumns 
    ) t where rowNumber=1 
+0

複雑に見えますが、 –

1

はほとんどのデータベースでは、あなたがANSI標準row_number()機能を使用することができます

SELECT SUBSTRING_INDEX(GROUP_CONCAT(day_id ORDER BY totalColumns DESC), ',', 1) as day_id, 
     section_mod_id, MAX(totalColumns) 
FROM (SELECT day_id, section_mod_id, count(*) as totalColumns 
     FROM supervision s INNER JOIN 
      section_mod m ON s.section = m.section_mod_id 
     GROUP BY day_id, section_mod_id 
    ) sm 
WHERE seqnum = 1 
GROUP BY section_mod_id 
+0

私はmysqlの解決策を試しましたが、このエラーが発生しました "キーワード 'order'の近くに不正な構文があります –

+0

最初のクエリエラー"式が期待されました(近い "(位置18)) 予期しないトークン(位置 "18") このタイプの句は以前に解析されました(位置19の "SELECT"の近く) エイリアスが以前に見つかりました(位置164の "seqnum"の近く) 予期しない閉じ括弧位置312に) エイリアスは以前に見つかりました(位置314の "sm"の近く) –

+0

2番目のエイリアスが以前に見つかりました(98の "section_mod_id"の近く) 138) 予期しないトークン( "("の近くの138位) このタイプのcl auseは以前に解析されました。 (位置139の "SELECT"の近く) 予期しない閉じ括弧。 (近くの ")"の位置336) エイリアスが見つかりました。 (位置338の "sm"の近く) このタイプの句は以前に解析されました。 (位置360の "GROUP BY"の近く) 認識できないステートメントタイプ。 (位置360の "GROUP BY"の近く) –

関連する問題