Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL Server显示视图以在父级和子级显示产品 我有一张这样的桌子:_Sql_Sql Server_Join_Hierarchy - Fatal编程技术网

SQL Server显示视图以在父级和子级显示产品 我有一张这样的桌子:

SQL Server显示视图以在父级和子级显示产品 我有一张这样的桌子:,sql,sql-server,join,hierarchy,Sql,Sql Server,Join,Hierarchy,我希望有一个横向表示用于报告,例如: +----+---------+---------+----------+ | ID | Name | level1 | level2 | +----+---------+---------+----------+ | 4 | T-shirt | Clothes | Null | | 5 | skirt | Clothes | Null | | 6 | pizza | Food | fastfood | |

我希望有一个横向表示用于报告,例如:

+----+---------+---------+----------+
| ID |  Name   | level1  |  level2  |
+----+---------+---------+----------+
|  4 | T-shirt | Clothes | Null     |
|  5 | skirt   | Clothes | Null     |
|  6 | pizza   | Food    | fastfood |
|  7 | snack   | Food    | fastfood |
+----+---------+---------+----------+

有人知道怎么做吗?

您可以使用两级
左连接:

select t.*,
       coalesce(tpp.name, tp.name) as level1,
       (case when tpp.name is not null then tp.name end) as level2
from t left join
     t tp
     on t.parent_id = tp.id left join
     t tpp
     on tp.parent_id = tpp.parent_id
where not exists (select 1
                  from t tc
                  where tc.parent_id = t.id);

我试过了,但没用。我也使用left连接表格,但结果是:ID--Name--level1--level2 4 T恤衣服空5裙子衣服空6比萨快餐7零食快餐我想表明level1是最高的家长level@AnnYoah . . . 我修改了答案,使值的顺序相反。
select t.*,
       coalesce(tpp.name, tp.name) as level1,
       (case when tpp.name is not null then tp.name end) as level2
from t left join
     t tp
     on t.parent_id = tp.id left join
     t tpp
     on tp.parent_id = tpp.parent_id
where not exists (select 1
                  from t tc
                  where tc.parent_id = t.id);