在使用mysql的情况下的情况

时间:2012-02-13 06:35:13

标签: mysql sql case

我有3列doc_datechem_datest_date

所有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

我想像这样编写select子句

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

如果某些案例陈述在同一日期有一个条目,例如{01} 02'doc_datest_date都存在,则应将其各自的计数添加到最终{{1} }表示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表的值是1.因此,最终的值将成为它们的加法,这是3

同样的规则适用于其他人。

任何建议如何在SQL中实现此输出?或者其他任何方式?

1 个答案:

答案 0 :(得分: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       

我在这里处理一个含糊不清的问题,因此需要澄清,