sql >> データベース >  >> RDS >> Oracle

現在のグループに応じて、最初の日付を取得するSQLクエリ(〜コントロールブレーク)

    更新 OPのコメントに基づく新しい回答。

    ANALYTICを使用できます 関数ROW_NUMBER およびLAG 。グループメソッドの開始のようなもの:

    SQL> WITH DATA AS(
      2  SELECT 100 EmployeeID, 'IT' Department, to_date('01.07.2014','DD.MM.YYYY') dt FROM dual UNION ALL
      3  SELECT 100, 'IT', to_date('01.08.2014','DD.MM.YYYY') dt from dual union all
      4  select 100, 'IT', to_date('01.09.2014','DD.MM.YYYY') dt from dual union all
      5  SELECT 100, 'HR', to_date('01.10.2014','DD.MM.YYYY') dt from dual union all
      6  select 100, 'HR', to_date('01.11.2014','DD.MM.YYYY') dt from dual union all
      7  SELECT 100, 'CC', to_date('01.12.2014','DD.MM.YYYY') dt from dual union all
      8  select 100, 'IT', to_date('01.01.2015','DD.MM.YYYY') dt from dual union all
      9  select 100, 'IT', to_date('01.02.2015','DD.MM.YYYY') dt from dual
     10  )
     11  SELECT EmployeeID,
     12    Department,
     13    DT
     14  FROM
     15    (SELECT *
     16    FROM
     17      (SELECT t.*,
     18        CASE
     19          WHEN Department = lag(Department) over (PARTITION BY EmployeeID ORDER BY dt)
     20          THEN 0
     21          ELSE 1
     22        END gap
     23      FROM DATA t
     24      ) T
     25    WHERE GAP = 1
     26    ORDER BY DT DESC
     27    )
     28  WHERE ROWNUM = 1
     29  /
    
    EMPLOYEEID DE DT
    ---------- -- ---------
           100 IT 01-JAN-15
    
    SQL>
    

    古い答え

    たとえば、

    SQL> WITH DATA AS(
      2  SELECT 100 EmployeeID, 'IT' Department, to_date('01.07.2014','DD.MM.YYYY') dt FROM dual UNION ALL
      3  SELECT 100, 'IT', to_date('01.08.2014','DD.MM.YYYY') dt from dual union all
      4  select 100, 'IT', to_date('01.09.2014','DD.MM.YYYY') dt from dual union all
      5  SELECT 100, 'HR', to_date('01.10.2014','DD.MM.YYYY') dt from dual union all
      6  select 100, 'HR', to_date('01.11.2014','DD.MM.YYYY') dt from dual union all
      7  SELECT 100, 'CC', to_date('01.12.2014','DD.MM.YYYY') dt from dual union all
      8  select 100, 'IT', to_date('01.01.2015','DD.MM.YYYY') dt from dual union all
      9  select 100, 'IT', to_date('01.02.2015','DD.MM.YYYY') dt from dual
     10  )
     11  SELECT*
     12  FROM
     13    (SELECT t.*,
     14      row_number() OVER(PARTITION BY department ORDER BY dt DESC) rn
     15    FROM DATA t
     16    )
     17  WHERE rn = 1
     18  /
    
    EMPLOYEEID DE DT                RN
    ---------- -- --------- ----------
           100 CC 01-DEC-14          1
           100 HR 01-NOV-14          1
           100 IT 01-FEB-15          1
    
    SQL>
    


    1. 異なる列と2つのテーブルからデータを選択します

    2. Amazonec2のリモートpostgresqlサーバーに接続します

    3. MariaDBサーバー10.5の新機能

    4. MYSQLで特定の顧客を選択しますか?