使用union all查询列两次

时间:2016-08-15 05:06:54

标签: sql sql-server tsql

我正在尝试做一个联合所有生成报告数据,下面是我到目前为止,它显示了我想要的所有数据,但我无法获取相同行中的数据,它产生了两行在相应列中最小为null。我希望有一种方法可以让我将数据放在同一行?

select account, campaign, sale, date
from
(
SELECT CHACCOUNTNO as account, CONTSUPREF as campaign,null as sale, ONDATE as date
FROM            dbo.MKTDW
WHERE        (RESULTCODE = 'D01') and CONTACT IN ('Campaign ID')
group by CHACCOUNTNO, CONTSUPREF, ONDATE

UNION ALL

SELECT CHACCOUNTNO as account, null as campaign, CONTSUPREF as sale, ONDATE as date
FROM            dbo.MKTDW
WHERE        (RESULTCODE = 'D01') and CONTACT IN ('Order')
group by CHACCOUNTNO, CONTSUPREF, ONDATE
)account
group by account,campaign,sale,date
order by account

当前结果:

account                 campaign   sale      date                    
A2043056003(2IJUMI M    NULL       N177618   2014-07-21 00:00:00.000
A2043056003(2IJUMI M    LT08704    NULL      2014-07-21 00:00:00.000

预期结果:

A2043056003(2IJUMI M)LT08704 N177618 2014-07-21 00:00:00.000

1 个答案:

答案 0 :(得分:0)

答案很简单。如果您想要以水平方式显示某些内容,请使用JOIN而不是SET运算符。代码列在下面,经过测试,在SSMS中完美运行。 :)

--create table structure
create table dbo.MKTDW 
(   CHACCOUNTNO varchar(100), 
    CONTSUPREF varchar(10), 
    RESULTCODE varchar(10), 
    CONTACT varchar(50), 
    ONDATE datetime)
go

--insert sample data
insert dbo.MKTDW 
select 'A2043056003(2IJUMI M)', 'N177618', 'D01', 'Order', '2014-07-21 00:00:00.000'
union all
select 'A2043056003(2IJUMI M)', 'LT08704', 'D01', 'Campaign ID', '2014-07-21 00:00:00.000'
union all
select 'B2043056003(2IJUMI M)', 'M000000', 'D01', 'Order', '2014-07-21 00:00:00.000'
union all
select 'B2043056003(2IJUMI M)', 'X111111', 'D01', 'Campaign ID', '2014-07-21 00:00:00.000'


--below is the solution
select  a.CHACCOUNTNO as account, 
        a.CONTSUPREF as campaign, 
        b.CONTSUPREF as sale, 
        a.ondate as date        
from dbo.MKTDW as a
join dbo.MKTDW as b
on a.CHACCOUNTNO = b.CHACCOUNTNO
where   a.CONTACT = 'campaign id' 
        and b.CONTACT = 'order' 
        and a.RESULTCODE = 'D01' 
        and b.RESULTCODE = 'D01'

<强>结果:

enter image description here