连接表SQL Server

时间:2016-06-06 18:17:44

标签: sql-server

是否可以使用子查询的结果集对行进行计数(我正在使用视图)?

假设我有

表1

  • t1id

表2

  • id,t1id_Parent,t1id_Child

表3

  • t1id

我查询

select
    t1.t1id as id,
    stuff((select ', ' + CAST(CASE WHEN t2.t1id_Child is not null THEN t2.t1id_Child ELSE '0' END AS varchar) from Table1 t where t.t1id_Parent = t1.t1id for xml path('')),1,2,'')  as ids
FROM
    Table1 as t1
LEFT OUTER JOIN 
    Table1 AS t2 ON t1.t1id = t2.t1id_Parent

所以我将所需的id组合成一个字符串,在名为“ids”的列中看起来像'1,2,5,9'正常工作,但我现在需要做的是这个查询

select
    t1.t1id as id,
    stuff((select ', ' + CAST(CASE WHEN t2.t1id_Child is not null THEN t2.t1id_Child ELSE '0' END AS varchar) from Table1 t where t.t1id_Parent = t1.t1id for xml path('')),1,2,'')  as ids
FROM
    Table1 as t1
LEFT OUTER JOIN 
    Table2 AS t2 ON t2.t1id_Parent = t1.t1id
LEFT OUTER JOIN 
    (select count(t1id) as rows_count, t1id 
     from Table3
     group by t1id) as docs ON docs.t1id in (ids)

使用临时列从第3个表中检索行计数但是我收到错误的无效列名'ids'

这是可能的,还是我需要首先运行该查询,然后返回并运行一个新的查询第三个表的计数?

我需要的结果是

Table1.t1id,count(Table3.t1id)

Table3.t1id来自Table1.t1id,所有Table2.t1id_Child关系来自Table1.t1id = Table2.t1id_Parent

我想不可能,但是它部分地与CTE合作,我现在得到的列表说我有这个'15673,15690,90987,45058'然后我可以对第三列进行查询但是得到了错误

WITH items AS
(
select
a.ItemID,
stuff(
(select ',' +
CAST(
CASE WHEN b.[ChildItemID] is not null 
THEN b.[ChildItemID] ELSE 0 END AS varchar)
    from Table2 t2 
    where t2.[ParentItemID] = a.ItemID
    for xml path('')
),1,2,'')
select
items.*,
docs.docs_count
from items
LEFT OUTER JOIN (
select count([DocID]) as docs_count from Table3
group by DocID
) as docs ON docs.ItemID in (items.ItemID)

Conversion failed when converting the nvarchar value '15673,' to data type int.

请注意,问题不是连接,我得到了预期的结果,以逗号分隔的值列表,当我尝试在“作为docs on docs.ItemID in(items。)中使用逗号分隔值时出现问题。 ItemIDs)“

0 个答案:

没有答案