没有总和的多行

时间:2014-04-10 14:36:53

标签: 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() ]%'

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 | NULL    | data | .....
NULL  | NULL | ext_ref | data | .....

我想

dim_2 | dim_3 | ext_ref | data |...
----------------------------------
dim_2 | NULL | ext_ref | data | .....

任何帮助将不胜感激

我正在使用MS SQL Server

吉姆

1 个答案:

答案 0 :(得分:0)

如果我理解得很好,可以通过这种方式简化。

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)