SQL:对数据进行分组

SQL : Grouping the Data

CREATE TABLEsample  
(  
Term NVARCHAR(100),  
Year NVARCHAR(50),  
Location NVARCHAR(100)  );  
INSERT INTO sample VALUES('1','1997','New York');  
INSERT INTO sample VALUES('1','1997','New York');  
INSERT INTO sample VALUES('1','1997','New York');  
INSERT INTO sample VALUES('1','1997','London');  
INSERT INTO sample VALUES('1','1997','London');  
INSERT INTO sample VALUES('1','1996','London');  
INSERT INTO sample VALUES('1','1996','London');  
INSERT INTO sample VALUES('1','1998','New York');  
INSERT INTO sample VALUES('1','1998','New York');     

我的结果集应该是这样的:

Term |Year | Location
----------------------
1    | 1997 | New York/London <--show like this if an year contains more than one location   
1    | 1996 | London  
1    | 1998 | New York 

下面的查询给了我想要的结果 SQL fiddle :

WITH CTE AS (  
    SELECT DISTINCT * FROM sample
)
SELECT A.Term, A.Year, A.Location 
FROM CTE A 
INNER JOIN  (SELECT Term, Year FROM CTE GROUP BY Term, Year HAVING COUNT(Year)=1) B 
    ON A.Term=B.Term and A.Year=B.Year 
UNION 
SELECT Term, Year, CASE WHEN COUNT(Term) > 1 THEN 'New York/London' END as Location 
FROM CTE 
GROUP BY Term,Year 
HAVING COUNT(Term)> 1

还有更好的选择吗?

试试这个:

SELECT 
    [Term],
    [Year],
    STUFF((
            SELECT '/' + [Location]
            FROM [sample] S1
            WHERE S1.Term = S2.Term AND S1.[Year] = S2.[Year]
            GROUP BY S1.Term, S1.[Year], S1.[Location]
            FOR XML PATH ('')
          ), 1, 1, '') AS [Location]
FROM [sample] S2
GROUP BY [Term], [Year]

希望对您有所帮助。

尝试使用 for xml path

select distinct Term,Year ,
stuff(
      (select distinct '/' +Location from sample 
            t2 where t1.Year=t2.Year and t1.Term=t2.Term 
                     for xml path('')
       ),1,1,''
     ) as xx
from sample t1
order by Year

sql-fiddle

试试这个

Select 
    [term],
    [year],
    somename((
            Select '/' + [Location]
            From [sample] c1
            Where c1.Term = c2.Term AND c1.[Year] = c2.[Year]
            Group by c1.Term, c1.[Year], c1.[Location]
            For XML PATH ('')
          ), 1, 1, '') AS [Location]
From [sample] c2
Group by [Term], [Year]