Tsql 构建一个查询,根据列中的值提取记录
我的表有一个父/子关系,沿着parent.id、id行。还有一列包含一个数量,另一个id表示一个父级,如下所示: 这应该显示的是ID 1是父母,ID 2和3是属于ID 1的孩子,ID 1、2和3都属于祖父母100 我想知道是否有任何孩子或家长的QTY=0,与该家长关联的所有其他id是什么,以及与该祖父母关联的所有其他家长是什么 例如,我希望看到一份报告,其中显示: 非常感谢您为构建MS SQL 2000(是的,我知道)查询以处理此问题提供的任何帮助 试试这个Tsql 构建一个查询,根据列中的值提取记录,tsql,sql-server-2000,Tsql,Sql Server 2000,我的表有一个父/子关系,沿着parent.id、id行。还有一列包含一个数量,另一个id表示一个父级,如下所示: 这应该显示的是ID 1是父母,ID 2和3是属于ID 1的孩子,ID 1、2和3都属于祖父母100 我想知道是否有任何孩子或家长的QTY=0,与该家长关联的所有其他id是什么,以及与该祖父母关联的所有其他家长是什么 例如,我希望看到一份报告,其中显示: 非常感谢您为构建MS SQL 2000(是的,我知道)查询以处理此问题提供的任何帮助 试试这个 select * from tabl
select * from tablename a
where exists (select 1 from tablename x
where x.parent_id = a.parent_id and qty = 0)
例如:
;with cte as
( select 1 id,1 parent_id, 1 qty, 100 org
union all select 2,1,0,100
union all select 3,1,4,100
union all select 4,4,1,101
union all select 5,4,2,101
union all select 6,6,1,102
union all select 7,6,0,102
union all select 8,6,1,102
)
select * from cte a
where exists (select 1 from cte x
where x.parent_id = a.parent_id and qty = 0)
谢谢,我错报了我的SQL版本。MS SQL 2000不支持CTE。@用户1729889,我正在使用CTE演示我的查询,您不必在此处使用CTE,请检查更新的答案
select * from tablename a
where exists (select 1 from tablename x
where x.parent_id = a.parent_id and qty = 0)
;with cte as
( select 1 id,1 parent_id, 1 qty, 100 org
union all select 2,1,0,100
union all select 3,1,4,100
union all select 4,4,1,101
union all select 5,4,2,101
union all select 6,6,1,102
union all select 7,6,0,102
union all select 8,6,1,102
)
select * from cte a
where exists (select 1 from cte x
where x.parent_id = a.parent_id and qty = 0)