Sql查询根据日期进行数据处理

时间:2017-03-28 07:40:53

标签: mysql

Table

我有一张这样的桌子。现在我想在单行中显示不同状态的相同日期总数。 该查询应该是什么?

预期结果

Created | Total1 | Total2 | Total3

2017-02-28 | 1 | 1 | 2

2 个答案:

答案 0 :(得分:1)

你可以使用一笔金额用于每个状态和组的情况

select 
      created
    , sum( case when story_status ='Draft' then total else 0 end ) as Draft_count
    , sum( case when story_status ='Private' then total else 0 end ) as Private_count
    , sum( case when story_status ='Published' then total else 0 end ) as Published_count
from my_table 
group by created

答案 1 :(得分:0)

这将为每个创建日期提供一行,每个story_status都有列:

SELECT
    `created`,
    SUM(if(`story_status` = 'Draft',`total`,0)) as `Total Draft`,
    SUM(if(`story_status` = 'Private',`total`,0)) as `Total Private`,
    SUM(if(`story_status` = 'Published',`total`,0)) as `Total Published`
FROM table
GROUP BY `created`
ORDER BY `created`
相关问题