cte,union,加入sql server

时间:2017-07-17 14:14:06

标签: sql sql-server sql-server-2008 sql-server-2008-r2

1   Pakistan    karachi 92
**2 Pakistan    Multan  92**
3   Pakistan    Sahiwal 92
4   Pakistan    Lahore  92
5   India       Mumbai  5541
6   India       Delhi   5541
7   India       Goa     5541
8   india       Amberser 5541
9   pakistan    Quetta  92

我现在有了这个结果,我想要从上表格式

id    column_name
1      pakistan
       karachi
       Multan
       Sahiwal
       Lahore
2      india
       Mumbai
       Delhi
       Goa
       Amberser

我希望代码与cte,union,join

2 个答案:

答案 0 :(得分:2)

示例表脚本

    DECLARE @Table1 TABLE 
        (Id int, name varchar(8), sname varchar(8), val int)
    ;

    INSERT INTO @Table1

    VALUES
    (1, 'Pakistan', 'karachi', 92),
    (1, 'Pakistan', 'karachi', 92),
        (2, 'Pakistan', 'Multan', 92),
        (3, 'Pakistan', 'Sahiwal', 92),
        (4, 'Pakistan', 'Lahore', 92),
        (5, 'India', 'Mumbai', 5541),
        (6, 'India', 'Delhi', 5541),
        (7, 'India', 'Goa', 5541),
        (8, 'india', 'Amberser', 5541),
        (9, 'pakistan', 'Quetta', 92)

SQL DEMO

脚本

   Select 
    CASE WHEN name  = Cname then ID ELSE NULL END ID,
    Cname from  (
    select DENSE_RANK()OVER( order by val )ID,
    name,
    Cname,
    val
             from @Table1
    CROSS APPLY 
    (values ('name',name), 
            ('sname',sname))CS(COL,Cname)
    GROUP BY name,Cname,val
    )T
    ORDER BY name DESC,CASE WHEN NAME = Cname then 0 ELSE 1 END 
;

答案 1 :(得分:1)

尝试 DENSE_RANK()

SELECT DENSE_RANK() OVER (ORDER BY your_numeric_column) as rank_id,
       country_name
FROM YourTable