简体   繁体   中英

SQL - Partition by - from Oracle to SQL server

I have two tables as below:

create table emp
  ( empno      NUMBER(4)    constraint E_PK primary key
  , job        VARCHAR2(8)
  , deptno     NUMBER(2)    default 10
  ) ;
create table departments
   ( deptno NUMBER(2)     constraint D_PK primary key
  , dname  VARCHAR2(10)
  ) ;

In Oracle, I have a query to show all employee with these position title of each department

select d.dname as department
   ,      e.job   as job
   ,      e.ename as emp
  from   emp e
        PARTITION BY (JOB)
         right outer join
        departments d
         using (deptno)
   order  by department, job;

And the result:

DEPARTMENT JOB      EMP
---------- -------- --------
ACCOUNTING Designer Chris
                    Peter
           Manager  Mike
           Tester   null
           TRAINER  null
HR         Designer
           Manager
           Tester
           TRAINER
SALES      Designer Black
           Manager  Jane
           Tester   Mary
                    Jack
                    Wil
                    Take
           TRAINER  null
TRAINING   Designer Jane
           Manager  null
           Tester   null
           TRAINER  Fake
                    Smart
                    Tom
                    Ana

Can I convert this query to SQL Server (2012 version) Thanks

You can join the 2 tables to get data. The difference will be that Department will be populated in each row.

SELECT
    d.dname AS Department
    ,e.Job
    ,e.ename AS Emp
FROM
    departments d
    LEFT OUTER JOIN emp e ON d.deptno = e.deptno
ORDER BY 
    d.dname
    ,e.Job
    ,2.ename

To get around this, you will have to tweak a bit:

SELECT 
    CASE WHEN RowNo = 1 THEN Department ELSE '' END AS Department
    ,Job
    ,Emp
FROM
    (SELECT
        d.dname AS Department
        ,e.Job
       ,e.ename AS Emp
       ,ROW_NUMBER() OVER (Partition By d.deptno ORDER BY e.Job,e.ename) RowNo
    FROM
       departments d
       LEFT OUTER JOIN emp e ON d.deptno = e.deptno
    ) Result
ORDER BY 
    Result.RowNo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM