在sql中加入两个select语句

时间:2013-05-08 10:45:50

标签: sql-server

我有两个select语句。第一个select返回2012年上一年的数据,而第二个select显示当前年份。我将如何加入这两个以获得我想要的输出。

select a.id, b.item, a.sum(qty) as 'yr1qty', a.yr1amt from table A
left join table B on a.code = b.code
where date between '04/01/2012' and '04/07/2012'
group by a.id, b. item

select a.id, b.item, a.sum(qty) as 'yr2qty', a.yr2amt from table A
left join table B on a.code = b.code
where date between '04/01/2013' and '04/07/2013'
group by a.id, b. item

期望的输出:

id   item       yr1qty    y1amt      yr2qty   yr2amt

01   item01      20       2000.00      5       500.00
02   item02                            8       400.00
03   item03      10       1250.00
04   item04       3        60.00       2       40.00
05   item05                            8       400.00

3 个答案:

答案 0 :(得分:1)

您应该能够使用完全外连接

将两者作为子查询加入
select 
    coalesce(a.id,b.id),
    coalesce(a.item,b.item), 
    yr1qty, 
    yr1amt, 
    yr2qty, 
    yr2amt
from
    (
    select a.id, b.item, a.sum(qty) as 'yr1qty', a.yr1amt from table A
    left join table B on a.code = b.code
    where date between '04/01/2012' and '04/07/2012'
    group by a.id, b. item) as a
    full outer join
    (
    select a.id, b.item, a.sum(qty) as 'yr2qty', a.yr2amt from table A
    left join table B on a.code = b.code
    where date between '04/01/2013' and '04/07/2013'
    group by a.id, b. item
    ) as b on a.id = b.id

答案 1 :(得分:0)

你需要两个吗?这是一个查询中的结果...

select a.id, b.item, 
a.sum(
    CASE WHEN date between '04/01/2012' and '04/07/2012'
        THEN qty 
        ELSE 0 
    END) AS 'yr1qty', a.yr1amt, 
a.sum(
    CASE WHEN date between '04/01/2013' and '04/07/2013'
        THEN qty 
        ELSE 0 
    END) AS 'yr2qty', a.yr2amt
from table A
left join table B on a.code = b.code
group by a.id, b.item

答案 2 :(得分:0)

您需要使用数据透视吗?

select id,item, yr1qty,yr1amt, yr2qty, yr2amt from
(
select a.id, b.item, a.qty, a.amt,
    case 
        when [date] between '2012-01-04' and '2012-07-01' then 'yr1qty'
        when [date] between '2013-01-04' and '2013-07-01' then 'yr2qty'
        else 'oor'
    end as yrqty,
    case 
        when [date] between '2012-01-04' and '2012-07-01' then 'yr1amt'
        when [date] between '2013-01-04' and '2013-07-01' then 'yr2amt'
        else 'oor'
    end as yramt



from A
left join B on a.code = b.code
) x
pivot (
    sum(qty) for yrqty in ([yr1qty],[yr2qty])
) qtyTotal
pivot (
    sum(amt) for yramt in ([yr1amt],[yr2amt])
) amtTotal