如何使用Pivot或Unpivot获得此结果

时间:2013-08-29 12:03:50

标签: sql-server tsql

我有一个查询,其中我得到这样的结果,我正在下面的结果集。但我需要得到如上一篇所示

SELECT DISTINCT                     LEFT(DATENAME(m, CONVERT(DATE, CONVERT(VARCHAR(10), fcp.DateKey))), 3) + ' ' + CONVERT(VARCHAR(4), year(convert(DATE, CONVERT(VARCHAR(10), fcp.DateKey)))) DatePeriod
        ,OM.HedisOCMKey AS OutComeMeasureKey
        ,(
            SELECT NumeratorSegmentCnt
            FROM Fact.HedisOCMSegments omse
            WHERE omse.SegmentLabel = 'Good'
                AND omse.HedisOCMKey = OM.HedisOCMKey
            ) AS Good
        ,0 AS Fair
        ,0 AS Poor
        ,0 AS 'NotCategorised'
                FROM fact.HEDISReport fcp WITH (NOLOCK)
    INNER JOIN fact.HedisOCM OM WITH (NOLOCK)
        ON OM.HEDISReportKey = fcp.HEDISReportKey
    INNER JOIN dim.ConditionMetric dc WITH (NOLOCK)
        ON dc.ConditionMetricID = OM.MetricID
    WHERE fcp.DateKey <= @i_ReportingPeriod

我的出局就像这样:

ConditionPrevalenceKey  PopulationConditionCnt  PrevalencePercent   DatePeriod  OutComeMeasureKey   Good    Fair    Poor    NotCategorised  NotTested   GoodPercentage  FairPercentage  PoorPercentage  NotCategorisedPercentage    NotTestedPercentage GoodRange   FairRange   PoorRange   NotCategorisedRange NotTestedRange  DerivedGoodValue    DerivedFairValue    DerivedPoorValue    DerivedNotCategorised   DerivedNotTested    ConditionMetricName


18018   252 0.53    Dec-12  34957   35  0   0   0   217 13.89   0   0   0   86.11   Good    Fair    Poor    NC  NoData  >= 1    0   0   NotCategorized  NotTested   Chlamydia  Screen

然后我怎么能得到这样的结果集:

year    Legend  percent count   Derived value field


Dec-12  Good    13.89   35  >= 1

Dec-12  Fair    0   0   0

Dec-12  Poor    0   0   0

Dec-12  NC  0   0   0

建议我???

1 个答案:

答案 0 :(得分:0)

我会使用UNPIVOT。这里有关于stackoverflow的UNPIVOT上有很多线程。这是一个example。这里的another非常相似。

以下是使用UNPIVOT解决您的具体问题的一般开始:

SELECT  [DatePeriod] ,
        [OutComeMeasureKey] ,
        [Legend] ,
        [Percent]
FROM    (SELECT DISTINCT
                LEFT(DATENAME(m, CONVERT(DATE, CONVERT(VARCHAR(10), fcp.DateKey))), 3) + ' ' + CONVERT(VARCHAR(4), YEAR(CONVERT(DATE, CONVERT(VARCHAR(10), fcp.DateKey)))) DatePeriod ,
                OM.HedisOCMKey AS OutComeMeasureKey ,
                (SELECT NumeratorSegmentCnt
                 FROM   Fact.HedisOCMSegments omse
                 WHERE  omse.SegmentLabel = 'Good' AND omse.HedisOCMKey = OM.HedisOCMKey
                ) AS Good ,
                0 AS Fair ,
                0 AS Poor ,
                0 AS 'NotCategorised'
         FROM   fact.HEDISReport fcp WITH (NOLOCK)
                INNER JOIN fact.HedisOCM OM WITH (NOLOCK) ON OM.HEDISReportKey = fcp.HEDISReportKey
                INNER JOIN dim.ConditionMetric dc WITH (NOLOCK) ON dc.ConditionMetricID = OM.MetricID
         WHERE  fcp.DateKey <= @i_ReportingPeriod
        ) AS sourcetable UNPIVOT ( [Percent] FOR Legend IN (Good, Fair, Poor, [NotCategorised]) ) AS unpvt