计算并集中两个值之间的差异

时间:2013-07-30 14:57:39

标签: sql sql-server-2008 union

我在下面的查询中告诉我人们在给定的时间段内开始和结束。

select UserId,
cast(sum(CommissionPerc)/100 as numeric(2,1)) as PlacementCount,
datename(mm,startdate) + ' ' + 'Start' as DataType
from PlacementConsultants 
group by userid, datename(mm,StartDate)
union
select UserId,
cast(sum(CommissionPerc)/100 as numeric(2,1)) as PlacementCount,
datename(mm,EndDate) + ' ' + 'End' as DataType
from Placements 
group by userid, datename(mm,EndDate)
order by datatype

输出如下:

791     4.0     May End
791     3.0     May Start
791     6.0     June End
791     2.0     June Start
791     1.0     July Start

但我还希望有一个列写为 MonthName Change

e.g。

791    4.0    May End
791    3.0    May Start
791    -1.0   May Change

最好的方法是什么?

2 个答案:

答案 0 :(得分:2)

您可以将查询嵌入CTE

;with CTE1 as (
    select
        UserId,
        cast(sum(CommissionPerc)/100 as numeric(2,1)) as PlacementCount,
        datename(mm,startdate) as Mon
    from PlacementConsultants 
    group by userid, datename(mm, StartDate)
), CTE2 as (
    select
        UserId,
        cast(sum(CommissionPerc)/100 as numeric(2,1)) as PlacementCount,
        datename(mm,EndDate) as Mon
    from Placements 
    group by userid, datename(mm, EndDate)
)
select C.UserId, C.PlacementCount, C.Mon + ' Start' as DataType
from CTE1 as C

union all

select C.UserId, C.PlacementCount, C.Mon + ' End' as DataType
from CTE2 as C

union all

select C1.UserId, C2.PlacementCount - C1.PlacementCount, C1.Mon + ' Change' as DataType
from CTE1 as C1
    inner join CTE2 as C2 on C2.UserId = C1.UserId and C2.Mon = C1.Mon
order by DataType

我也改变了union to union all,因为union会尝试消除你没有的重复行

答案 1 :(得分:1)

;with a as
(
select UserId,
cast(sum(CommissionPerc)/100 as numeric(2,1)) as PlacementCount,
datename(mm,startdate) as DataType
from PlacementConsultants 
group by userid, datename(mm,StartDate)
), b as
(
select UserId,
cast(sum(CommissionPerc)/100 as numeric(2,1)) as PlacementCount,
datename(mm,EndDate) as DataType
from Placements 
group by userid, datename(mm,EndDate)
)
select UserId, PlacementCount, DataType + ' Start' DataType
from a
union all
select UserId, PlacementCount, DataType + ' End' DataType
from b
union all
select a.UserId, b.PlacementCount- a.PlacementCount, a.DataType + ' Change' DataType
from a
join b
on a.userid = b.userid and a.DataType = b.DataType