日期:2014-05-18 浏览次数:20506 次
这样的效果?你把表对应名称换成你的那个就成了.. CREATE TABLE TB1(LevelId INT,NAME VARCHAR(4)) INSERT INTO TB1(LevelId,NAME) SELECT 1,'轻' UNION ALL SELECT 2,'中' UNION ALL SELECT 3,'重' CREATE TABLE TB2(DangerId INT,UserId INT,LeveLId INT) INSERT INTO TB2(DangerId,UserId,LeveLId) SELECT 1,4,1 UNION ALL SELECT 2,4,2 UNION ALL SELECT 3,4,3 UNION ALL SELECT 4,2,1 UNION ALL SELECT 5,2,1 UNION ALL SELECT 6,2,2 UNION ALL SELECT 7,2,2 UNION ALL SELECT 8,5,3 UNION ALL SELECT 9,2,3 UNION ALL SELECT 10,3,1 CREATE TABLE TB3(UserId INT,UserName VARCHAR(4)) INSERT INTO TB3(UserId,UserName) SELECT 2,'y' UNION ALL SELECT 3,'z' UNION ALL SELECT 4,'c' SELECT 5,'q' -------- SELECT * FROM TB1 SELECT * FROM TB2 SELECT * from TB3 ----查询 ;WITH DD AS( SELECT B.DangerId,A.UserName,B.LeveLId FROM TB3 A LEFT JOIN TB2 B ON A.UserId=B.UserId ) SELECT B.*,A.NAME FROM TB1 A LEFT JOIN DD B ON A.LeveLId=B.LeveLId ------- DangerId UserName LeveLId NAME ----------- -------- ----------- ---- 1 c 1 轻 4 y 1 轻 5 y 1 轻 10 z 1 轻 2 c 2 中 6 y 2 中 7 y 2 中 3 c 3 重 9 y 3 重 (9 行受影响)
------解决方案--------------------
少了个UNION ALL: SELECT 4,'c' SELECT 5,'q' 换成: SELECT 4,'c' UNION ALL SELECT 5,'q' q没插入进去 DangerId UserName LeveLId NAME ----------- -------- ----------- ---- 1 c 1 轻 4 y 1 轻 5 y 1 轻 10 z 1 轻 2 c 2 中 6 y 2 中 7 y 2 中 3 c 3 重 8 q 3 重 9 y 3 重 (10 行受影响)
------解决方案--------------------
SELECT isnull(LevelName,'') '程度',isnull(UserName,'') '姓名',isnull(COUNT(LevelName),'') as '次数' FROM tb_Danger LEFT JOIN tb_Level ON tb_Danger.LevelId = tb_Level.LevelId FULL JOIN tb_Users ON tb_Danger.UserId = tb_Users.UserId --AND Limit = 1 GROUP BY LevelName,UserName order by LevelName desc