日期:2014-05-17 浏览次数:20489 次
--CREATE TABLE News(ID INT, Title varchar(10), [Date] date)
--INSERT INTO News
--SELECT 1, 'ABCDE' ,'2012-3-1'
--UNION ALL
--SELECT 2, 'ABC' , '2012-3-1'
--create TABLE Category(ID INT , CategoryName VARCHAR(10))
--INSERT INTO Category
--SELECT 1, '类型1'
--UNION ALL
--SELECT 2 , '类型2'
--UNION ALL
--SELECT 3, '类型3'
--create TABLE CatNew(ID INT , NewsID INT , CategoryID INT )
--INSERT INTO CatNew
--SELECT 1 , 1 , 1
--UNION ALL
--SELECT 2 , 1 , 2
--UNION ALL
--SELECT 3 , 2 , 3
--UNION ALL
--SELECT 4 , 2 , 1
WITH huang AS (
SELECT a.id,a.title,a.[date],c.CategoryName
FROM news a
INNER JOIN catnew b ON a.id = b.newsid
INNER JOIN category c ON b.categoryid = c.id
)
SELECT a.id,a.title ,
stuff((select '_'+CategoryName from huang b
where b.id=a.id and b.id=a.id
for xml path('')),1,1,'') 'CategoryName'
FROM huang a
GROUP BY a.id,a.title
/*
id title CategoryName
----------- ---------- ----------------------------------------------------------------------------------------------------------------
1 ABCDE 类型1_类型2
2 ABC 类型1_类型3