我有一张桌子 如下
Code ActionType user Date
ABC 1 john 2012-09-09
BCD 2 john 2012-09-09
BCD 2 john 2012-10-09
我想得到基于用户的代码,我们可以在这里得到user ='john',并且从这里根据john的代码我将获得代码我应该得到总共1次出现和总共2次出现在一个单独的列和最近日期为2的单独列。我的deisred输出如下所示
Code NumberOf1s Number of 2s RECENTDateof1s RECENTDate of2s
BCD 0 1 NULL 2012-10-09
这是已尝试的代码
select code,ActionType,Count(*) as NumbOf1s from Table Where user='john' and _ActionType in(1,2)
GROUP BY ActionType,code
请帮助 感谢
答案 0 :(得分:0)
使用CASE WHEN
仅考虑聚合中的某些属性:
select
code,
count(case when actiontype = 1 then 1 end) as numberof1s,
count(case when actiontype = 2 then 1 end) as numberof2s,
max(case when actiontype = 1 then thedate end) as recentdateof1s,
max(case when actiontype = 2 then thedate end) as recentdateof2s
from mytable
where user = 'john'
and actiontype in (1,2)
group by code
order by code;
and actiontype in (1,2)
在这里是可选的,但可以加快查询速度。