还是我的苹果,梨的问题

redcola 2003-10-20 08:33:48
http://expert.csdn.net/Expert/topic/2355/2355965.xml?temp=.9733698
已知两个表
表一
a 苹果
a 梨
b 苹果
b 苹果
b 梨
表二为
a
b
c
现求表三 ,是这样求的
表二第一个值为a,则到表一中查找,共有两个a,苹果有一个,梨有一个,表三第一行值为1 1 2
表二第二个值为b,到表一中查找,共有三个b,苹果有两个,梨有一个,表三第二行值为2 1 3
表二第三个值为c,到表一中查找,没有一个c ,苹果没有,梨没有,其行值为0 0 0
所以应得表三值为

苹果 梨 总数
1 1 2
2 1 3
0 0 0
想用SQL语句求出来。
在哪里加语句啊。
我使用了大力的,很管用又方便,
select
(select count(*) from 表一 where 列2='苹果' and 列=表二.列) 苹果,
(select count(*) from 表一 where 列2='梨' and 列=表二.列) 梨,
(select count(*) from 表一 where 列=表二.列) 总数
from 表二
----------------------------
现在想,如果要表的三个值均为零时,刚不显示000
要表的结果如下:
苹果 梨 总数
1 1 2
2 1 3
在大力的这个句子上怎么加呢?
我写了一个:

select
(select count(*) from 表一 where 列2='苹果' and 列=表二.列) 苹果,
(select count(*) from 表一 where 列2='梨' and 列=表二.列) 梨,
(select count(*) from 表一 where 列=表二.列) 总数
from 表二
where ((select count(*) from 表一 where 列2='苹果' and 列=表二.列)<>0
or
(select count(*) from 表一 where 列2='梨' and 列=表二.列)<>0
or
(select count(*) from 表一 where 列=表二.列)<>0 )

这样写太麻烦,有简单的么,最好就在大力的这个句子上改了。


...全文
61 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
pengdali 2003-10-20
  • 打赏
  • 举报
回复
select 列1,sum(case when 列2='苹果' then 1 else 0 end) 苹果,sum(case when 列2='梨' then 1 else 0 end) 梨,count(*) 合计 from 表一 group by 列1
pengdali 2003-10-20
  • 打赏
  • 举报
回复
select
sum(case when 列2='苹果' then 1 else 0 end) 苹果,
sum(case when 列2='梨' then 1 else 0 end) 梨,
count(*) from 表一 group by 列1

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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