需要SQL查询sql server

时间:2015-01-22 13:03:20

标签: sql sql-server

大师, 我有如下数据

Id  Stage   Name    Stage1dt    stage2dt    stage1amt   stage2amt
1     A     tst1    23-01-2015  01-12-2015  100         200
2     B     tst2    23-02-2015  02-12-2015  2323        232
3     A     tsr2    25-01-2015  null        200         400

我需要SQL来给出阶段明智的计数并将给定月份的相应阶段数量相加。例如,如果我将月份作为Jan(1)...我需要输出如下...请帮助

        A    B
Count   2    1
Amount  300  200

查询这样的事情..

(Select count(1) from tbl where stage = 'A' and month(stage1dt) = @month) Acount,

(select count(1) from tbl where stage = 'B'  and month(stage2dt) = @month)  BCount,

1 个答案:

答案 0 :(得分:1)

我认为你需要这样的东西?

Declare @Month varchar(20)
Set @Month = 'February'

Select 'Count', A, B From

(Select Stage, Count(Stage) stgamt
From tbl
where DateName(Month,case Stage when 'A' then Stgdt1 when 'B' then Stgdt2 end) = @Month
Group By Stage) as s
PIVOT
(SUM(Stgamt) for Stage in (A, B)) as piv

UNION

Select 'Amount', A, B From

(Select Stage, Case Stage when 'A' then Sum(amt1) when 'B' then Sum(amt2) end as Amount
From tbl
where DateName(Month,case Stage when 'A' then Stgdt1 when 'B' then Stgdt2 end) = @Month
Group By Stage) as s
PIVOT
(SUM(Amount) for Stage in (A, B)) as piv

如果您只想将月份输入为int

,请将DateName更改为Month