如何在不使用插入查询的情况下在sql中插入虚拟行?

时间:2017-04-19 12:51:07

标签: mysql sql insert union

我有以下查询

select '2016' as yr,warehouse as product,sum(answertext) p1 ,
round((sum(abc)/(select sum(abc) from [table 1])*100),2) p2
 from [table 1]
group by warehouse
order by p1 desc
limit 10 

显示以下输出

yr        product            prodnum    prodper

2016     Harness Extra      94427        10.4
2016     Lumax              54534         9.6
.. 
... 
..
...
..
..
..
2016   Capreno              534533        4.6

现在我必须手动为2015年和2014年的虚拟值插入prdonum和prodper的自定义值,我在另一个单词表中 如何在单个查询中执行此操作?任何帮助都会很棒? 它应采用以下格式

    yr      product              prodnum      prodper

    2016   Harness Extra         94427       10.4  // from table
    2015   Harness Extra         32453       5.7  <- custom value to be inserted
    2014   Harness Extra         21215       2.3  <- custom value to be inserted
    2016   Lumax                 78994       8.76  // from table
    2015   Lumax                 43435       4.77 <- custom value to be inserted
    2014   Lumax                 15522       3.55 <- custom value to be inserted
    ..
    ..


    ..
<totally 30 rows>

1 个答案:

答案 0 :(得分:0)

如果你在另一个表中有它,可以使用union语句吗?

Select * from 
 (
select '2016' as yr,warehouse as product,sum(answertext) p1 ,
round((sum(abc)/(select sum(abc) from [table 1])*100),2) p2
         from [table 1]
        group by warehouse

UNION ALL            

    select '2015' as yr,warehouse as product,sum(answertext) p1 ,
    round((sum(abc)/(select sum(abc) from [table 1])*100),2) p2
     from [table 2]
    group by warehouse

    UNION ALL

    select '2014' as yr,warehouse as product,sum(answertext) p1 ,
    round((sum(abc)/(select sum(abc) from [table 1])*100),2) p2
     from [table 3]
    group by warehouse
    )a
 order by p1 desc