日期:2014-05-19  浏览次数:20551 次

一道让人头痛的题目
QXXH       QXMC
1   发文填写
2   发文审批
3   收文填写
4   收文审批

权限-人员对应表XT_QXRY,如果某人有某个权限,则在此表有条记录(序号,权限序号,用户名称)
XH   QXXH   YHMC
1   2   张三
2   3   张三
3   1   李四
4   3   李四
5   4   李四
我想产生一个这样的查询:列出所有用户有哪些权限,同时列出所有的权限.
查询结果如下:
XH     QXXH             QXMC       YHMC               是否有此权限
1         1       发文填写         张三               false
2         2       发文审批         张三               true
3         3       收文填写         张三               true
4         4       收文审批         张三               false  
5         1       发文填写         李四               true
6         2       发文审批         李四               false
7         3       收文填写         李四               true
8         4       收文审批         李四               true

------解决方案--------------------
create table A(QXXH int, QXMC nvarchar(10))
insert A select 1, '发文填写 '
union all select 2, '发文审批 '
union all select 3, '收文填写 '
union all select 4, '收文审批 '

create table B(XH int, QXXH int, YHMC nvarchar(10))
insert B select 1, 2, '张三 '
union all select 2, 3, '张三 '
union all select 3, 1, '李四 '
union all select 4, 3, '李四 '
union all select 5, 4, '李四 '

select tmp.*, 是否有此权限=case when B.XH is null then 'False ' else 'True ' end from
(
select * from
(select distinct YHMC from B) as B
cross join A
)tmp
left join B on tmp.QXXH=B.QXXH and tmp.YHMC=B.YHMC

--result
YHMC QXXH QXMC 是否有此权限
---------- ----------- ---------- ------
李四 1 发文填写 True
李四 2 发文审批 False
李四 3 收文填写 True
李四 4 收文审批 True
张三 1 发文填写 False
张三 2 发文审批 True
张三 3 收文填写 True
张三 4 收文审批 False

(8 row(s) affected)

------解决方案--------------------
select a.xh,b.qxxh,b.qxmc,a.yhmc,qxf=case when b.qxxh is null then 0 else 1 end
from xt_qxry a full join table1 on a.qxxh=b.qxxh
------解决方案--------------------
create table tmp1(QXXH int,QXMC nvarchar(20))
go

create table tmp2(XH int,QXXH int,YHMC nvarchar(20))

go

select c.*,是否有权限=case when d.xh is null then 'false ' else 'true ' end
from
(
select * from tmp1 a cross join(select distinct yhmc from tmp2) b
) c

left join tmp2 d on c.qxxh=d.qxxh