2017-04-19 44 views
3

我有以下查詢如何在不使用插入查詢的情況下在sql中插入虛擬行?

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定製值以及我在另一個單詞表中提供的產品 如何在單個查詢中執行此操作?任何幫助將是偉大的? 應該在以下格式

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

創建包含所有可能年份的幫助表。外面加入那張桌子。 – jarlh

回答

0

如果你擁有了它在另一張表,也許用聯合聲明?

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

它顯示的錯誤:錯誤地使用union和order – goonernike

+0

我已經更新回答 – tommylux

相關問題