0

如何显示列 SUM 和列百分比不起作用?

为了简单的解释:

我有 2 个 SQL 语句

SELECT TOP 100 PERCENT COUNT(CodeAll) AS Total, CodeAll, Description,
LEFT(CodeAll, 1) AS Code
FROM Data WHERE DATE BETWEEN '2013/03/01 00:00:00' AND '2013/03/01 23:59:00'
AND (CodeAll Is Not Null)
GROUP BY CodeAll, Description ORDER BY Code
ASC 

结果

Total | CodeAll | Description | Code
-------------------------------------
3       1c         Test          1
3       1b         Test2         1
10      1a         Test3         1
2       2a          Test4        2
5       2b         Test5         2
5       3a         Test6         3
3       3b         Test7         3

查询 #2:

SELECT COUNT(CodeAll) AS SumCall, LEFT(CodeAll, 1) AS Code FROM Data 
WHERE DATE BETWEEN '2013/03/01 00:00:00' AND '2013/03/01 23:59:00' 
AND (CodeAll Is Not   Null) GROUP BY LEFT(CodeAll, 1)`

结果

SumCall| Code 
16       1
7        2
8        3

我想组合2 query成 1 个查询来生成:

 Total | CodeAll | Description | Code | SUM  | Percentage 
    3       1c         Test          1       16    18.75 %
    3       1b         Test2         1       16    18.75 %
    10      1a         Test3         1       16    62.5 % 
    2       2a          Test4        2        7    28.57 %
    5       2b         Test5         2        7    71.43 %
    5       3a         Test6         3        8    62.5 %
    3       3b         Test7         3        8    37.5 %

询问??
请帮忙

4

1 回答 1

1

SQL小提琴

MS SQL Server 2008 架构设置

CREATE TABLE TEST_TAB
    ([Total] int, [CodeAll] varchar(2), [Description] varchar(5), [Code] int)
;

INSERT INTO TEST_TAB
    ([Total], [CodeAll], [Description], [Code])
VALUES
    (3, '1c', 'Test', 1),
    (3, '1b', 'Test2', 1),
    (10, '1a', 'Test3', 1),
    (2, '2a', 'Test4', 2),
    (5, '2b', 'Test5', 2),
    (5, '3a', 'Test6', 3),
    (3, '3b', 'Test7', 3)
;

查询 1

select v.*, 100.0 * v.total/v.group_total percentage
  from (
    select t.*, 
           sum(total) over(partition by code) group_total
      from TEST_TAB t
  ) v

结果

| TOTAL | CODEALL | DESCRIPTION | CODE | GROUP_TOTAL |      PERCENTAGE |
------------------------------------------------------------------------
|     3 |      1c |        Test |    1 |          16 |           18.75 |
|     3 |      1b |       Test2 |    1 |          16 |           18.75 |
|    10 |      1a |       Test3 |    1 |          16 |            62.5 |
|     2 |      2a |       Test4 |    2 |           7 | 28.571428571428 |
|     5 |      2b |       Test5 |    2 |           7 | 71.428571428571 |
|     5 |      3a |       Test6 |    3 |           8 |            62.5 |
|     3 |      3b |       Test7 |    3 |           8 |            37.5 |
于 2013-03-20T09:32:40.280 回答