0

我有两个选择语句。1stselect返回 2012 年的数据,而 2ndselect显示当前年份。我将如何加入这两个以获得我想要的输出。

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
4

3 回答 3

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
于 2013-05-08T10:54:47.667 回答
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
于 2013-05-08T10:55:40.527 回答
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
于 2013-05-08T11:12:51.100 回答