如何使用CTE从没有公共列的两个表中获取记录

时间:2017-07-20 11:45:41

标签: sql sql-server sql-server-2012

用户表详细信息

  

用户ID值(abc,xyz,abc,sdf)

主表详情

  

(中旬,优先级)的值(101,1),(102,2),(101,1),(103.1)

我需要根据用户ID(用户名是用户名)按优先级(优先级为int)分组,例如优先级为1,然后'打开'打开'优先级= 2然后&#39 ;关闭'等等使用CTE(公用表表达式)

Select * from users
userid
abc
xyz
abc
sdf


Select * from master
mid  Priority
101    1
102    2
101    1
103    1

(优先级1 =开放2 =已关闭)

期望输出:

Userid  count(mid) Priority
abc     2          Open
xyz     1          Closed
sdf     1          Open

1 个答案:

答案 0 :(得分:0)

试试这个:

use db_test;
go
drop table dbo.users;
create table dbo.users
(
    userid varchar(max) not null
)
;

insert into dbo.users
values 
        ('abc'),
        ('xyz'),
        ('sdf')


create table dbo.master
(
    mid int not null,
    Priority int not null
)
;

insert into dbo.master
values
    (101,    1),
    (102,    2),
    (101,    1),
    (103,    1)
;

with cte1 as (
    select userid, row_number() over(order by userid asc) as rn 
    from dbo.users
), cte2 as (
    select mid, priority, dense_rank() over(order by mid asc) as rn
    from dbo.master
)
select a.userid, count(*) as [count(mid)], b.priority
from cte1 a join cte2 b on a.rn = b.rn
group by a.userid, b.priority