SQL查询基础 - 在不同日期返回多个数据

时间:2013-10-28 19:58:44

标签: sql

基本的SQL查询有问题,我需要总结很多信息,而我正在使用的查询是:

SELECT date, id, actions
FROM accounts 
WHERE (date between '2013-07-01' and '2013-9-30') AND (id in (---ids---));

现在我正在

date 1    id1   actions
date 2    id1   actions
date 3    id1   actions
date 4    id1   actions
date 5    id1   actions
date 6    id1   actions

date 1    id2   actions
date 2    id2   actions
date 3    id2   actions
date 4    id2   actions
date 5    id2   actions
date 6    id2   actions

我想要的是

date 1    id1   actions  id2  actions
date 2    id1   actions  id2  actions
date 3    id1   actions  id2  actions
date 4    id1   actions  id2  actions
date 5    id1   actions  id2  actions
date 6    id1   actions  id2  actions

最简单的方法是什么?

1 个答案:

答案 0 :(得分:2)

假设在给定日期只有一个id1id2,那么这是一个数据透视查询。某些数据库中有一个特殊的语法用于数据透视,但以下工作原理如下:

SELECT date,
       max(case when id = 'id1' then id end) as id1,
       max(case when id = 'id1' then actions end) as id1_actions,
       max(case when id = 'id2' then id end) as id2,
       max(case when id = 'id2' then actions end) as id2_actions
FROM accounts 
WHERE (date between '2013-07-01' and '2013-9-30') AND (id in (---ids---))
group by date
order by date;

请注意,date是某些数据库中的关键字,因此您需要以某种方式引用它(例如使用双引号,后引号或方括号)。