0

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

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

例如

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

解决这个问题的最佳方法是什么?

4

2 回答 2

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 更改为 union all,因为 union 将尝试消除您没有的重复行

于 2013-07-30T15:05:07.507 回答
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
于 2013-07-30T15:15:47.673 回答