vendredi 8 mai 2015

SQL: Pulling info from a column and building new columns

I’m building a report where I am combining two different databases. As it is this query is functional.

select  t.[Test ID],
          [Business Group],
          [Department],
          [SubGroup],
          [Regulation Source],
          [Risk Level],
          [Regulation Title],
          [Data Points],
          [Control Test Question(s)],
          [Compliance Test Questions],
        r.MonthSubmitted,
          CompliancePassPercent,
          ControlPassPercent


from DefaultOperationalRisk..RCSATracker             T (nolock)
left join DefaultOperationalRisk..TB_FLODTestResults R (nolock)

on T.[Test ID]=R.[TestName]

where t.[Control Testing Status 3] not like 'test retired' 
or    t.[Control Testing Status 3] not like 'pending test development'
and r.MonthSubmitted > GETDATE()-90

The problem is that the columns from TB_FLODTestResults should look more like this:

AprilCompResults|AprilControlResults|MarchCompResults|MarchControlResults|

Instead these columns come out looking like this:

MonthSubmitted|CompliancePassPercent|ControlPassPerent|

This way means a lot of my information is duplicated. I need the results to be based on the Test ID column from the RCSATracker database.

The thread from this question game me a start (SQL: Move data in one column to different columns).

SELECT a.TestName, 
       b.ControlPassPercent AS 'April Control Results', 
       c.ControlPassPercent AS 'March Control Results', 
       d.ControlPassPercent AS 'February Control Results' 
FROM   (SELECT DISTINCT testname 
        FROM   DefaultOperationalRisk..TB_FLODTestResults) a 
       LEFT JOIN (SELECT testname, 
                         ControlPassPercent
                  FROM   DefaultOperationalRisk..TB_FLODTestResults
                  WHERE  MonthSubmitted = 'March 2015') b 
              ON b.TestName = a.TestName 
       LEFT JOIN (SELECT TestName, 
                         ControlPassPercent
                  FROM   DefaultOperationalRisk..TB_FLODTestResults 
                  WHERE  MonthSubmitted = 'April 2015') c 
              ON c.TestName = a.TestName 
       LEFT JOIN (SELECT TestName, 
                         ControlPassPercent 
                  FROM   DefaultOperationalRisk..TB_FLODTestResults 
                  WHERE  MonthSubmitted = 'February 2015') d 
              ON d.TestName = a.TestName 

I would like the monthly results/columns to have a three month look back not including the current month. So basically a rolling query. Also I have not been able to fit the code I wrote from the forum thread into my query at the top.

Aucun commentaire:

Enregistrer un commentaire