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

sql语句问题,有兴趣的帮忙看看!
我有两个表user和info
user包括username(char)   headuser(char)   unit(char)
info包括detaile(text)   inputuser(char)

user   内容为
A     null   开发部
B     A         null  
C     A         null  
D     null   销售部

info   内容为

good     A
bad       C
cool     D
petty   B


要得到的结果为
开发部   3
销售部   1

这个sql怎么写呀!
那位有兴趣帮帮忙!
急等,验证后马上给分!

------解决方案--------------------
SELECT
CASE ISNULL(U1.unit, ' ') WHEN ' ' THEN U2.unit ELSE U1.unit END AS 部门,COUNT(*) AS 数量
FROM
user U1
LEFT JOIN user U2 ON U1.headuser=U2.username
GROUP BY CASE ISNULL(U1.unit, ' ') WHEN ' ' THEN U2.unit ELSE U1.unit END
------解决方案--------------------
select unit,count(1)
from
info left join
(
select t.username,
case isnull(t.unit, ' ')
when ' ' then v.unit
else t.unit
end as unit
from users t
left join users v on t.headuser=v.username
) as tt on username=inputuser
group by unit
------解决方案--------------------
没看lz说明,语句改为这样

select unit,count(unit) from
(select * from info a left join
(select username, isnull(unit,(select unit from user1 where username=c.headuser)) as unit from user1 c) as b
on a.inputuser=b.username) as d group by unit