查询Sql百分比(CLOSED)

时间:2013-03-20 09:04:17

标签: sql

如何显示列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 %

查询??
请帮忙

1 个答案:

答案 0 :(得分:1)

SQL Fiddle

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

<强> Results

| 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 |