读书人

哥哥们有兴趣帮忙看看这个视图如何做

发布时间: 2012-03-05 11:54:02 作者: rapoo

哥哥们有兴趣帮忙看看这个视图怎么做!
我有两个表,一个data表存文章,一个user表存人员信息
类似这样
data表
charid(文章id) input(上报人) status(是否发表1为发表、0为上报)
1 AA 0
2 BB 1
3 CC 1
4 DD 1
5 EE 1
6 FF 0
7 GG 0

user
userid(用户id) corpid(公司名) headuser(上级人员)
AA IBM null
BB null AA
CC SUN null
DD null CC
EE ABC null
FF null EE


GG LTD null

要得到的视图是
公司名 上报数量 发表数量
IBM 2 1
SUN 2 2
ABC 2 1
LTD 1 0

这个sql怎么做?

[解决办法]
上报数量怎么计算的?
为什么是
2
2
2
1

[解决办法]
Select
C.corpid,
SUM(Case D.status When 0 Then 1 Else 0 End) As 上报数量,
SUM(Case D.status When 1 Then 1 Else 0 End) As 发表数量
From
(
Select corpid, userid From [user] Where headuser Is Null
Union
Select A.corpid, B.userid From [user] A Inner Join [user] B On A.userid = B.headuser
) C
Left Join
data D
On C.userid =D.input
Group By
C.corpid


PS:
果好象有
[解决办法]
eyan_810810(小妍妍) ( ) 信誉:100 2007-07-27 14:46:06 得分: 0


如果公司为空也要看headuser


------
句有考的。
[解决办法]
鱼写的没有问题,只是LZ的要求没有解释清楚

借鱼的例子
/* 创建表
Create Table data
(charid Int,
input Varchar(10),
status Bit)
Insert data Select 1, 'AA ', 0
Union All Select 2, 'BB ', 1
Union All Select 3, 'CC ', 1
Union All Select 4, 'DD ', 1
Union All Select 5, 'EE ', 1
Union All Select 6, 'FF ', 0
Union All Select 7, 'GG ', 0

Create Table [user]
(userid Varchar(10),
corpid Varchar(10),
headuser Varchar(10))
Insert [user] Select 'AA ', 'IBM ', null
Union All Select 'BB ', null, 'AA '
Union All Select 'CC ', 'SUN ', null
Union All Select 'DD ', null, 'CC '
Union All Select 'EE ', 'ABC ', null
Union All Select 'FF ', null, 'EE '
Union All Select 'GG ', 'LTD ', null
*/

Select
C.corpid,


--SUM(Case D.status When 0 Then 1 Else 0 End)
Count(*) As 上报数量,
SUM(Case D.status When 1 Then 1 Else 0 End) As 发表数量
From
(
Select corpid, userid From [user] Where headuser Is Null
Union All
Select A.corpid, B.userid From [user] B Inner Join [user] A on A.userid = B.headuser and B.corpid is Null
) C
Left Join
data D
On C.userid =D.input
Group By
C.corpid

即可
[解决办法]
sp4(1), 你,我也了,已改了。 :)

读书人网 >SQL Server

热点推荐