如何将结果连接到一行? (TSQL)

时间:2016-02-25 16:26:38

标签: sql-server tsql concatenation union

我找到了以下链接:SQL, How to Concatenate results?

但是,我的用例略有不同。我有大约64个字段(允许值YN),这些字段都被称为" QryGroup"接下来是一个数字。

我已经编写了一个查询(查询1)来创建另一个查询(查询2),该查询将返回QryGroup至少有一个值的所有列名=' Y'在一个已定义的子集中。

然而,为了做到这一点,它创建了大量的联合以便将所有的值组合在一起。查询1正在以这样的方式创建查询2,即查询2为我提供了我正在查找的结果,但所有这些都在单独的行中。我想将它们连接成一行,以便我可以将它们放入查询3中,以便仅显示子集中至少有一个记录具有' Y'它们的价值。

举个例子,我不想要一个包含以下列的表:

Item Name    Item Description    QryGroup1    QryGroup2    QryGroup3    QryGroup4    QryGroup5    QryGroup6    QryGroup7    QryGroup8

当只有QryGroup1,4和6有一个非 - ' N'值。相反,我想拥有

Item Name    Item Description    QryGroup1    QryGroup4    QryGroup6

我有以下查询,在这种情况下,将返回值

`QryGroup1`
`QryGroup4`
`QryGroup6`

查询2:

select 'QryGroup1' FROM OITM
WHERE QryGroup1 <> 'N'  AND oitm.itemcode in ([subset])
GROUP BY QryGroup1 HAVING COUNT(*)<> 0 
union all
select 'QryGroup2' FROM OITM
WHERE QryGroup2 <> 'N'  AND oitm.itemcode in ([subset])
GROUP BY QryGroup2 HAVING COUNT(*)<> 0 
union all
select 'QryGroup3' FROM OITM
WHERE QryGroup3 <> 'N'  AND oitm.itemcode in ([subset])
GROUP BY QryGroup3 HAVING COUNT(*)<> 0 
union all
select 'QryGroup4' FROM OITM
WHERE QryGroup4 <> 'N'  AND oitm.itemcode in ([subset])
GROUP BY QryGroup4 HAVING COUNT(*)<> 0 
union all
select 'QryGroup5' FROM OITM
WHERE QryGroup5 <> 'N'  AND oitm.itemcode in ([subset])
GROUP BY QryGroup5 HAVING COUNT(*)<> 0 
union all
select 'QryGroup6' FROM OITM
WHERE QryGroup6 <> 'N'  AND oitm.itemcode in ([subset])
GROUP BY QryGroup6 HAVING COUNT(*)<> 0 
union all
select 'QryGroup7' FROM OITM
WHERE QryGroup7 <> 'N'  AND oitm.itemcode in ([subset])
GROUP BY QryGroup7 HAVING COUNT(*)<> 0 
union all
select 'QryGroup8' FROM OITM
WHERE QryGroup8 <> 'N'  AND oitm.itemcode in ([subset])
GROUP BY QryGroup8 HAVING COUNT(*)<> 0 

我不认为我上面发布的链接会在我的情况下起作用,因为我试图连接Union ed结果,而不仅仅是正常结果。

如果您需要更多说明,请告诉我。我还包括了&#34;查询1&#34;如果它有帮助:

SELECT  replace(replace(replace(stuff(   (select cast('union all select ''' as nvarchar(max)) 
+ column_name + 
cast(''' FROM OITM' as nvarchar(max))
+ char(13) + 
cast(' WHERE ' as nvarchar(max))
+ column_name + 
cast( ' <> ''N''  AND oitm.itemcode in (subset)' as nvarchar(max))
+char(13) +
cast(' GROUP BY ' as nvarchar(max)) 
+ column_name   +
cast(' HAVING COUNT(*)<> 0 ' as nvarchar(max))  
            from information_schema.columns
            where table_schema = 'dbo'
            and   table_name = 'OITM'
            and   column_name like 'QryGroup%%'
            for xml path(''))
        ,1,10,''), '&lt;', '<'), '&gt;', '>'), '&#x0D;', char(13))

0 个答案:

没有答案