日期:2014-05-18  浏览次数:20586 次

帮忙看一下这个查询

id pid(父ID) title
-------------------------
1 0 abc
2 1 def
3 0 ghi
4 2 mnq
5 1 rst
6 2 xyz

怎么得到

id pid title
-------------------------
1 0 abc 
2 1 def
5 1 rst
3 0 ghi
4 2 mnq
6 2 xyz

也就是说把 pid(不为0)的都放在一起 并放在它的父ID下面

如图,所 pid=1都放在一起了,并在 id=1这一行的下面

------解决方案--------------------
是不是要求没说清,按你的要求这样不也可以
create table #a(id int,pid int,title varchar(10))
insert #a select
1,0,'abc' insert #a select
2,1,'def' insert #a select
3,0,'ghi' insert #a select
4,2,'mnq' insert #a select
5,1,'rst' insert #a select
6,2,'xyz' 
select * from #a order by (case when pid=1 then pid else id end)
1 0 abc
2 1 def
5 1 rst
3 0 ghi
4 2 mnq
6 2 xyz


------解决方案--------------------
CREATE TABLE T
(
ID INT,
PID INT,
TITLE VARCHAR(20)
)

INSERT INTO T
SELECT 1,0, 'abc ' UNION ALL
SELECT 2,1, 'def ' UNION ALL
SELECT 3,0, 'ghi ' UNION ALL
SELECT 4,3, 'mnq ' UNION ALL
SELECT 5,1, 'rst ' UNION ALL
SELECT 6,3, 'xyz '
GO

CREATE FUNCTION F_AILAOPO()
RETURNS @t TABLE(ID INT, PID INT, TITLE VARCHAR(20), LEVEL INT, BIAO INT )
AS
BEGIN
DECLARE @i INT
SET @i = 0
INSERT INTO @t
SELECT *,@i,(SELECT COUNT(1) FROM (SELECT * FROM T A WHERE NOT EXISTS ( SELECT * FROM T B WHERE B.ID = A.PID)) B WHERE A.ID> B.ID)
FROM
(
SELECT * FROM T A WHERE NOT EXISTS ( SELECT * FROM T B WHERE B.ID = A.PID)
) A

WHILE @@ROWCOUNT <> 0
BEGIN
SET @i = @i + 1
INSERT INTO @t
SELECT B.ID,B.PID,B.TITLE,@i,A.BIAO FROM @t A, T B WHERE A.ID = B.PID AND A.LEVEL = @i - 1
END
RETURN
END
GO

SELECT ID,PID,TITLE FROM DBO.F_AILAOPO() ORDER BY BIAO,LEVEL,ID

DROP FUNCTION F_AILAOPO
DROP TABLE t


ID PID TITLE
----------- ----------- --------------------
1 0 abc
2 1 def
5 1 rst
3 0 ghi
4 3 mnq
6 3 xyz

(所影响的行数为 6 行)