SQL中的树视图

时间:2013-04-25 19:37:21

标签: sql treeview

是否有一种使用SQL Server Management Studio中的“输出到文本”在SQL Select语句中执行扩展树视图的简单方法?

输入表

GRP NAME ITEM1 ITEM2
--- ---- ----- -----
 1   AB   100   200
 1   AC   150   200
 1   AD   175   200
 2   BC   200   220
 2   BD   NULL  NULL

期望的输出

GRP 1
+-- AB
+    +-- ITEM1: 100
+    +-- ITEM2: 200
+-- AC
+    +-- ITEM1: 150
+    +-- ITEM2: 200
+-- AD
+    +-- ITEM1: 175
+    +-- ITEM2: 200

GRP 2
+-- BC
+    +-- ITEM1: 200
+    +-- ITEM2: 220
+-- BD

由于 jlimited

1 个答案:

答案 0 :(得分:0)

这样做(你需要忽略输出中的2,3,4列,它们是为了排序):

select DISTINCT 'GRP ' + convert(varchar(10), GRP), convert(int, GRP), ' ', 0 from table1
UNION ALL
select '+-- ' + [NAME], convert(int, GRP), [name], 1 from table1
UNION ALL
select '+    +-- ITEM 1: ' + [ITEM1], convert(int, GRP), [name], 2 from table1 where ITEM1 IS NOT NULL
UNION ALL
select '+    +-- ITEM 2: ' + [ITEM2], convert(int, GRP), [name], 3 from table1 where ITEM2 IS NOT NULL
ORDER BY 2,3,4

SQL Fiddle