选择2个已分组的记录,然后将它们放在旁边的2列中

时间:2013-08-13 21:33:53

标签: sql sql-server database pivot

在表格中我们有学校的数据:

 ID | Name | City
------------------  
  1    A     X          
  2    B     X    
  3    C     Z
  4    D     Z

我想列出同一城市的每两所学校的名单:

Name1 | Name2
--------------  
  A      B          
  C      D    

我选择了同一个城市的学校:

 SELECT Name FROM Schools
    Group by City
    Having City = City

这是对的吗?如何将2个匹配的学校放在一张新桌旁?

由于

3 个答案:

答案 0 :(得分:4)

更新另一种方法

如果你坚持分组

,可以采取一种方法
SELECT City,
       MIN(Name) Name1,
       MAX(Name) Name2
  FROM Schools
 GROUP BY City
-- HAVING COUNT(*) > 1

另一种方式

SELECT City,
       MIN(CASE WHEN rnum = 1 THEN Name END) Name1,
       MIN(CASE WHEN rnum = 2 THEN Name END) Name2
  FROM
(
  SELECT s.*, ROW_NUMBER() OVER (PARTITION BY City ORDER BY Name) rnum
    FROM Schools s
) q
 GROUP BY City

示例输出:

| CITY | NAME1 | NAME2 |
------------------------
|    X |     A |     B |
|    Z |     C |     D |

这是 SQLFiddle 演示

答案 1 :(得分:1)

SELECT a.Name, b.Name
FROM Schools a JOIN Schools b ON a.City = b.City 
          AND a.ID != b.ID 
          AND a.Name < b.Name;

这将返回同一城市的所有学校对,而不仅仅是每个城市的一对学校。

答案 2 :(得分:0)

如果一个城市包含超过2所学校,则以下查询不保证将返回哪两所学校:

SELECT      S1.Name,
            S2.Name
FROM        (
                SELECT      MIN(ID) ID,
                            City
                FROM        @Schools
                GROUP BY    City
            ) S
INNER JOIN  @Schools S1 ON S.ID = S1.ID
INNER JOIN  @Schools S2 ON ( S.City = S2.City AND S.ID != S2.ID )