将特定行转换为标头,并将特定行转换为标头值SQL Server

时间:2020-04-30 09:05:55

标签: sql sql-server toad

我在Toad SQL数据库表中有以下数据。让我们说表名称为tblSample。

ID     NAME   COVERMONTH  EFFECTIVEDATE  TERMDATE  PAIDAMOUNT  EARNEDAMOUNT
1546871 SAMPLE1    202001   1-Aug-14     31-Dec-99       5122.12     5111.02  
1065418 SAMPLE2    202001   1-Jan-15     31-Dec-99           0           0
1546871 SAMPLE1    202002   1-Aug-14     31-Dec-99        5122.12     5111.02  
1065418 SAMPLE2    202002   1-Jan-15     31-Dec-99        3211.21     3211.21

在上面的数据中,我有2个项目ID的数据。在实际情况下,项目ID的计数将是动态的

注意:COVERMONTH将是动态值。它们每个月都在变化。

所需的输出如下所示

ID    NAME    EFFECTIVEDATE    TERMDATE    202001    202002   202003 --- all the rows are completed
1546871 SAMPLE1   1-Aug-14      31-Dec-99  5122.12   5111.02   5122.12 ------
1065418 SAMPLE2   1-Jan-15      31-Dec-99      0     3211.21   3012.12 ------

简单来说,我需要将COVERMONTH作为列标题,并将EARNEDAMOUNT作为特定ID的行值。

在示例表ID中,特定ID的NAME,EFFECTIVEDATE和TERMDATE相同,但PAIDAMOUNT和EARNEDAMOUNT逐月变化。

对于获得最终结果的任何帮助,我们深表感谢。

2 个答案:

答案 0 :(得分:1)

如果知道所需的月份,则可以使用条件聚合:

select ID, NAME, EFFECTIVEDATE, TERMDATE,
       sum(case when COVERMONTH = 202001 then EARNEDAMOUNT end) as ea_202001,
       sum(case when COVERMONTH = 202002 then EARNEDAMOUNT end) as ea_202002,
       . . .
from t
group by ID, NAME, EFFECTIVEDATE, TERMDATE

答案 1 :(得分:0)

尝试这个:

输入

@ COVERMONTH1和@ COVERMONTH2

Create Proc usp_myproject
     @COVERMONTH1 int
    ,@COVERMONTH2 int
AS
    Set nocount on

    Select ID, [NAME], EFFECTIVEDATE, TERMDATE,
           sum(case when COVERMONTH = @COVERMONTH1 then EARNEDAMOUNT end) as COVERMONTH_One,
           sum(case when COVERMONTH = @COVERMONTH2 then EARNEDAMOUNT end) as COVERMONTH_Two
    From t
    Group by ID, NAME, EFFECTIVEDATE, TERMDATE