2012-02-13 96 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