在这种情况下如何使用数据透视表进行计算?

时间:2016-01-14 11:04:32

标签: c# sql sql-server sql-server-2008

如何从给定数据中获得以下结果。

报告

$scope.countries.forEach(...)

我需要计算结果,如

-------------------------------------------------
 ID    |    Name          |    Status
-------------------------------------------------
  1    |     A            |    Inprogress
  2    |     A            |    Inprogress
  3    |     A            |    Complete

SQL:

---------------------------------------------
Name    |   Total  | Complete  |  Remaining
---------------------------------------------
   A    |    3     |   1       |    2      

2 个答案:

答案 0 :(得分:1)

您不需要使用PIVOT运营商。尝试使用subqueryCROSS APPLY运算符来解决您的任务

;WITH test_data AS(
    SELECT 1 AS id, 'A' AS NAME, 'Inprogress' AS [status]
    UNION ALL
    SELECT 2, 'A', 'Inprogress'
    UNION ALL
    SELECT 3, 'A', 'Complete'
    UNION ALL
    SELECT 4, 'B', 'Complete'
)

SELECT DISTINCT
       name,
       T3.*
FROM test_data AS T
CROSS APPLY (SELECT COUNT(*) AS total,
                    SUM(CASE WHEN T2.status = 'Complete' THEN 1 ELSE 0 END) AS complete, 
                    SUM(CASE WHEN T2.status = 'Inprogress' THEN 1 ELSE 0 END) AS remaining 
             FROM test_data AS T2
             WHERE T2.name = T.name) AS T3

答案 1 :(得分:1)

您可以采取一些方法。此示例使用CASE expressions。如果您不熟悉该概念,则CASE允许您以条件方式返回所选值。我已将您的样本数据转换为表变量:

示例数据

/* Creating sample data inside a table variable makes it
 * easy to share.
 */
DECLARE @Sample TABLE
    (
        ID            INT,
        Name        VARCHAR(50),
        [Status]    VARCHAR(50)
    )
;

/* Sample values taken from OP.
 */
INSERT INTO    @Sample
    (
        ID,
        Name,
        [Status]
    )
VALUES
    (1, 'A', 'Inprogress'),
    (2, 'A', 'Inprogress'),
    (3, 'A', 'Complete')
;

CASE为所需的状态返回1,为其他所有内容返回0。对结果求和可提供小计。

/* Using CASE to return conditional sub totals.
 */
SELECT
    Name,
    COUNT([Status])                                                AS Total,
    SUM(CASE WHEN [Status] = 'Complete'    THEN 1 ELSE 0 END)        AS Complete,
    SUM(CASE WHEN [Status] = 'Inprogress'    THEN 1 ELSE 0 END)    AS Remaining
FROM
    @Sample
GROUP BY
    Name
;