使用TSQL从平面数据创建分层数据

时间:2017-04-03 21:25:54

标签: sql sql-server tsql

给定一个包含以下数据的表:

ID  ParentID    Level   Letter  Country         City
---------------------------------------------------------
1   NULL        0       A       NULL            NULL
2   1           1       NULL    Afghanistan     NULL
3   2           2       NULL    NULL            Kabul
4   2           2       NULL    NULL            Kandahar
6   1           1       NULL    Australia       NULL
7   6           2       NULL    NULL            Canberra
8   6           2       NULL    NULL            Sydney
9   NULL        0       B       NULL            NULL
10  9           1       NULL    Belgium         NULL
11  10          2       NULL    NULL            Antwerp
12  10          2       NULL    NULL            Bruges
13  10          2       NULL    NULL            Brussels

我可以在一个sql语句中返回以下数据吗?

output$fullscreen_map <- renderLeaflet({
  points <- points_reactive()

  points %>%
    leaflet() %>% 
    addTiles() %>%
    fitBounds(~min(lon), ~min(lat), ~max(lon), ~max(lat)) %>%
    registerPlugin(textPathPlugin) %>%
    onRender("function(el, x, data) {
                data = HTMLWidgets.dataframeToD3(data);
                data = data.map(function(val) { return [val.lat, val.lon]; });
                var layer = L.polyline(data);
                layer.on('mouseover', function () {
                this.setText('  ►  ', {repeat: true, attributes: {fill: 'blue'}});
                });
                layer.on('mouseout', function () {
                this.setText(null);
                });
                layer.addTo(this);
    }", data = points)

})

1 个答案:

答案 0 :(得分:3)

Declare @YourTable table (Country varchar(50), City varchar(50))
Insert Into @YourTable values
('Afghanistan','Kabul'),
('Afghanistan','Kandahar'),
('Australia'  ,'Canberra'),
('Australia'  ,'Sydney'),
('Belgium'    ,'Antwerp'),
('Belgium'    ,'Bruges'),
('Belgium'    ,'Brussels')

; with cte0 as (
                Select Lvl0 = cast(Left(Country,1) as varchar(50))
                      ,Lvl1 = cast(Country as varchar(50))
                      ,Lvl2 = cast(City as varchar(50))
                      ,ID0  = Dense_Rank() over (Order By Left(Country,1))
                      ,ID1  = Dense_Rank() over (Order By Country) + 100
                      ,ID2  = Dense_Rank() over (Order By City) + 10000
                 From  @YourTable
               )
Select Distinct ID=ID0,ParentID=null,Level=0,Letter=Lvl0,Country=null,City=null,Path=concat('',Lvl0) from cte0
Union All
Select Distinct ID=ID1,ParentID=ID0,Level=1,Letter=null,Country=Lvl1,City=null,Path=concat('',Lvl0,' > ',Lvl1) from cte0
Union All
Select Distinct ID=ID2,ParentID=ID1,Level=2,Letter=null,Country=null,City=Lvl2,Path=concat('',Lvl0,' > ',Lvl1,' > ',Lvl2) from cte0
Order By Path

<强>返回

enter image description here

相关问题