求助:CASE WHEN 里面怎么加DISTINCT的功能啊

demonwinwin 2005-08-09 09:05:52
问:
例如 有表如下
id name photo
01 aaa 1
01 aaa 2
02 bbb 1
02 bbb 3
03 ccc 3
.....
sql里面用到
count( case when photo='1' or photo='2' then 1 else null end )PHnumber
但是这样就得count得3了

01 aaa 1
01 aaa 2
02 bbb 1
可是我想把id一样的只算一条
只想得
01
02
怎么写?

...全文
3925 14 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
demonwinwin 2005-08-09
  • 打赏
  • 举报
回复
在此再次感谢各位解决了我的问题
demonwinwin 2005-08-09
  • 打赏
  • 举报
回复
谢谢 nebulaly(极高明而道中庸)
之前没注意到你写的id
count(distinct case when photo='1' or photo='2' then id else null end )PHnumber
可以
揭帖
nebulaly 2005-08-09
  • 打赏
  • 举报
回复
count(distinct case when photo='1' or photo='2' then id else null end )PHnumber

then 1 作count结果是1

then id应该就不是1了
demonwinwin 2005-08-09
  • 打赏
  • 举报
回复
to sasacat(傻傻猫) 谢谢你,这样可以
不过对不起
我之前没说清楚
我是想仅仅要count,不用把ID,NAME查出来,我是为了group by 用的(按照id第一位0/1/2...分组)
select substr(id,1,1)
,count(case when photo=1 or photo=2 then 1 else null end) PHnumber
,count(case when photo=3 then 1 else null end) PJnumber
from table
group by substr(id,1,1)
这样的结果没有distinct

是可以这样分开来查
..
select substr(id,1,1)
count(distinct(id))
from table where photo=1 or photo=2
group by substr(id,1,1)
...
select substr(id,1,1)
count(distinct(id))
from table where photo=3
group by substr(id,1,1)
...
再把结果合起来
不过速度应该会慢
所以我问大家能不能直接在count(case when )状态下用distinct的类似功能
sasacat 2005-08-09
  • 打赏
  • 举报
回复
select ID ,NAME, count(case when photo=1 or photo=2 then 1 else null end)PHnumber
from T_LOGIN_LOG
where photo in(1,2)
group by ID ,NAME

这样?ID NAME PHNUMBER
---------- ---------- ----------
01 aaa 2
02 bbb 1
demonwinwin 2005-08-09
  • 打赏
  • 举报
回复
to: sasacat(傻傻猫) 不是这个结果
我要的count结果是2条
01和02
to: nebulaly 不能这样用distinct,结果为1
nebulaly 2005-08-09
  • 打赏
  • 举报
回复


count(distinct case when photo='1' or photo='2' then id else null end )PHnumber

就可以了
sasacat 2005-08-09
  • 打赏
  • 举报
回复
你自己的语句查询出来不是
ID NAME PHNUMBER
---------- ---------- ----------
01 aaa 2
02 bbb 1
03 ccc 0

吗?你想要什么样的结果集啊?写个完整一点的看看啊
demonwinwin 2005-08-09
  • 打赏
  • 举报
回复
to: duanzilin(寻) sasacat(傻傻猫) 不能这样查的,这样结果是都是1
to:bobfang(匆匆过客) 我也知道这种方法,但是我要count(case when...)这种模式下用distinct
难道这的没法用吗?
bobfang 2005-08-09
  • 打赏
  • 举报
回复
如果是“photo里面等于1或2的话就把该id记入总数(不要相同的)”,应该是在where条件中对photo做限制,count时是count(distinct id)
sasacat 2005-08-09
  • 打赏
  • 举报
回复
count(distinct case when photo='1' or photo='2' then 1 else null end )PHnumber

这样就可以用了
沝林 2005-08-09
  • 打赏
  • 举报
回复
这样试试:
count(distinct (case when ...) )
demonwinwin 2005-08-09
  • 打赏
  • 举报
回复
我的意思是如果photo里面等于1或2的话
就把该id记入总数(不要相同的)
不能用z5wjz(z5wjz) 的case id='01'...

是有其他方法可以(先把所有photo等于1或2的id要出来,distinct,在count),但是我就是想问问能不能在case when 的情况里面在加上类似distinct的功能
z5wjz 2005-08-09
  • 打赏
  • 举报
回复
不太明白你的意思,我理解的好像是你case错了,你可以case id='01' then 1 else NULL end case

17,381

社区成员

发帖
与我相关
我的任务
社区描述
Oracle 基础和管理
社区管理员
  • 基础和管理社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧