2012-02-13 74 views
0

我有3列doc_datechem_datest_date情況下用mysql

所有3列屬於不同的表:

doc 
doc_date  count(x) 
01-02-2012  2 
02-02-2012  3 

chem 
chem_date  count(x) 
04-02-2012  1 
06-02-2012  0 

stock 
st_date  count(x) 
01-02-2012  1 
03-02-2012  5 

我想寫這樣

case doc_date 
    when '01' then count(x), 
    case chem_date 
    when '01' then count(x), 
    case st_date 
    when '01' then count(x) 
    end as '01', 
case doc_date 
    when '02' then count(x), 
    case chem_date 
    when '02' then count(x), 
    case st_date 
    when '02' then count(x) 
    end as '02', 

....up to 31 days 
SELECT子句

如果某些病例陳述在同一日期有條目,例如doc_datest_date都存在於'01-02-20 12' 然後它們各自的計數應該被添加到最終count(x)裝置count(x) + count(x)

所以,答案應該是:

01 02 03 04 05 06 07 08 09 10 11 12.. up to 31 days 
3 3 5 1  0       count(x) value for particular date 

輸出的說明:在此,日期01起始值爲2爲doc表和stock表的值爲1.因此,最終值將成爲它們的加法數3

相同的規則將適用於其他人。

任何建議如何在SQL中實現此輸出?或者其他方式?

+0

是的,我正在改進它.... – Java 2012-02-13 07:09:43

+2

基本上,如果你沒有改善它,沒有人會回答,因爲他們不會相信你會將他們的問題標記爲回答。所以這是爲了你自己的利益。 – 2012-02-13 07:27:08

回答

0

這裏是展示它是如何做一個僞代碼:

select 

case when date_format(doc_date,"%d") = '01' then sum_x else null end as '01', 
case when date_format(doc_date,"%d") = '02' then sum_x else null end as '02', 
--and etc 

from (

    select doc_date, sum(doc_x) as sum_x    --sum the x value 
    from 
    (

     select doc_date,doc_x       --combine all 3 table stuff 
     from doc a 

     union all 

     select chem_date,chem_x 
     from chem a 

     union all 

     select st_date,st_x 
     from st a 
    ) h 
    group by doc_date    --use first col name as the union's col name 

) g 
limit 1,1  

如果docchemst使用joins相結合,並有不同的模式,你可能需要做支點,或者使用多個連接到本身或使用case... when...

select 

case when date_format(doc_date,"%d") = '01' then sum_x else null end as '01', 
case when date_format(doc_date,"%d") = '02' then sum_x else null end as '02', 
--and etc 

from (

     select doc_date,        
       a_x + b_x + c_x as sum_x   --sum them according to date 
     from (select ... from doc where ...) a 
     left join (select ... from chem where ...) b on a.doc_date=b.doc_date and --some join condition 
     left join (select ... from st where ...) c on a.doc_date=c.doc_date and --some join condition 

) g 
limit 1,1  

我與這裏的曖昧問題的工作,所以需要澄清,

+0

你的方式絕對是好的,但我已經使用不同的條件加入了這些表格,在這裏我們已經使用了union all,(將doc,chem,stock視爲一個單獨的子句,就像這樣)select * from(select .....從doc左連接.....)以這種方式左連接(select * from chem left join ..),那麼如何在這些子句中包含您的答案? – Java 2012-02-13 08:13:30

+1

@PravinGate我會編輯我的答案 – cctan 2012-02-13 09:01:53

+0

我已經試過你的方式沒有限制1,1然後我得到一行,但sum_x的值爲26天的特定月顯示所有1-31天,它應該只顯示那個月的26號。? – Java 2012-02-13 10:42:35