Sum Union查询并获取每行的百分比

时间:2016-06-03 22:31:23

标签: mysql

我试图获得每行查询的百分比。所以我的问题是:

SELECT ITEM, AVG_VAL/sum(AVG_VAL) * 100 as PERCENT_TOTAL

FROM
(SELECT
'item 1' AS ITEM,
AVG(VAL) AS AVG_VAL

FROM TABLE1
WHERE DATE(t_stamp) BETWEEN '2016-06-02' AND '2016-06-02'

UNION ALL

SELECT
'item 2' AS ITEM,
AVG(VAL) AS AVG_VAL

FROM TABLE2
WHERE DATE(t_stamp) BETWEEN '2016-06-02' AND '2016-06-02') as t

第一个表(TABLE1)的数据是

    ITEM    |   AVG_VAL
    item 1  |   45,042,179

第二个表(TABLE2)的数据是

    ITEM    |   AVG_VAL
    item 2  |   30,428,453

我希望得到输出

ITEM    |   PERCENT_TOTAL
item 1  |       59.68
item 2  |       40.32

但是当我尝试按ITEM分组时

SELECT ITEM, AVG_VAL/sum(AVG_VAL) * 100 as PERCENT_TOTAL

FROM
(SELECT
'item 1' AS ITEM,
AVG(VAL) AS AVG_VAL

FROM TABLE1
WHERE DATE(t_stamp) BETWEEN '2016-06-02' AND '2016-06-02'

UNION ALL

SELECT
'item 2' AS ITEM,
AVG(VAL) AS AVG_VAL

FROM TABLE2
WHERE DATE(t_stamp) BETWEEN '2016-06-02' AND '2016-06-02') as t
GROUP BY ITEM

我得到了

ITEM    |   PERCENT_TOTAL
item 1  |       100
item 2  |       100

我也希望能显示percent_total列的总数,以便显示

ITEM    |   PERCENT_TOTAL
item 1  |       59.68
item 2  |       40.32
Total   |       100

1 个答案:

答案 0 :(得分:2)

这是单程......

SELECT x.*
     , ROUND(avg_val/total * 100,2) pct
  FROM
     ( SELECT * FROM table1
        UNION
       SELECT * FROM table2
     ) x
  JOIN 
     ( SELECT SUM(avg_val) total
         FROM 
            ( SELECT * FROM table1
               UNION
              SELECT * FROM table2
            ) n
     ) y