Sql 多行无和

Sql 多行无和,sql,Sql,又是我! 对于同一条记录,我有一个当前分布在两行的查询,我想按照下面的示例将其合并到一行 DECLARE @period_from INT SET @period_from = 201400 DECLARE @period_to INT SET @period_to = 201414 Declare @length INT Set @length = '12' DECLARE @query VARCHAR(MAX) SET @query = '%[^-a-zA-Z0-9() ]%' SE

又是我! 对于同一条记录,我有一个当前分布在两行的查询,我想按照下面的示例将其合并到一行

DECLARE @period_from INT
SET @period_from = 201400

DECLARE @period_to INT
SET @period_to = 201414

Declare @length INT
Set @length = '12'

DECLARE @query VARCHAR(MAX)
SET @query = '%[^-a-zA-Z0-9() ]%'

SELECT 
'dim_2' AS dim_2, 
NULL AS dim_3,
NULL AS ext_ref, 
* FROM table1 WHERE client = 'CL'AND period >= @period_from AND @period_to <= @period_to AND dim_2 LIKE @query AND voucher_no='170075928' AND agrtid='9662846'
UNION
SELECT 
NULL as dim_2,
'dim_3' AS dim_3,  
NULL AS ext_ref,
* FROM table1 WHERE client = 'CL'AND period >= @period_from AND @period_to <= @period_to AND dim_3 LIKE @query AND voucher_no='170075928'AND agrtid='9662846'
UNION
SELECT 
NULL AS dim_2, 
NULL AS dim_3,
'ext_ref' AS ext_ref,
* FROM table1 WHERE client = 'CL'AND period >= @period_from AND @period_to <= @period_to AND ext_ref LIKE @query AND voucher_no='170075928'AND agrtid='9662846'
我想要

dim_2 | dim_3 | ext_ref | data |...
----------------------------------
dim_2 | NULL | ext_ref | data | .....
任何帮助都将不胜感激

我正在使用MS SQL Server


吉姆

如果我理解得好的话,可以这样简化

select 
case when dim_2  LIKE @query then 'dim_2' end as dim_2,
case when dim_3 LIKE @query then 'dim_3' end as dim_3,
case when ext_ref LIKE @query then 'ext_ref' end as ext_ref,
*
FROM 
table1 
WHERE client = 'CL'
 AND period >= @period_from 
 AND @period_to <= @period_to 
 AND voucher_no='170075928'
 AND agrtid='9662846'
-- and maybe add
--(and dim_2 like @query or dim_3 like @query or ext_ref like @query)
选择
当dim_2与@query相似时,则“dim_2”以dim_2结尾,
当dim_3与@query相似时,则“dim_3”以dim_3结尾,
当ext_ref如@query,然后“ext_ref”以ext_ref结尾时,
*
从…起
表1
其中client='CL'
和周期>=@period\u自

和@period_表示当两行的值不同时会发生什么情况?谁赢了?@吉姆:看来你爱上了联合胶水。但是,这只会删除重复项。通过使用常数'dim_2'等,确保没有重复项。即使没有它们,在表1中的*中,您是否期望两条记录在所有列上完全相等?您的SQL语句有点自相矛盾。这是我从你那里读到的第二个请求。它们是非常技术性的,而且两种情况下你似乎都在错误的方向上思考。最好告诉我们有关表格内容以及您想要实际实现的目标。
select 
case when dim_2  LIKE @query then 'dim_2' end as dim_2,
case when dim_3 LIKE @query then 'dim_3' end as dim_3,
case when ext_ref LIKE @query then 'ext_ref' end as ext_ref,
*
FROM 
table1 
WHERE client = 'CL'
 AND period >= @period_from 
 AND @period_to <= @period_to 
 AND voucher_no='170075928'
 AND agrtid='9662846'
-- and maybe add
--(and dim_2 like @query or dim_3 like @query or ext_ref like @query)