fa fb
1 2
3 2
2 3
1 3用select fb, count(fb) as fbcount from table1 group by fb 的结果为fb fbcount
2 2
3 2但我希望得出以下结果:fb fbcount
2 2
3 1因为第4条记录的 fa为1已经出现过了, 不希望它再被统计到
1 2
3 2
2 3
1 3用select fb, count(fb) as fbcount from table1 group by fb 的结果为fb fbcount
2 2
3 2但我希望得出以下结果:fb fbcount
2 2
3 1因为第4条记录的 fa为1已经出现过了, 不希望它再被统计到
解决方案 »
- 这里的 where 100 in 的100怎么理解丫?
- 请教:数据库访问-从本地数据库到远程数据库连接的转换
- 请问,这个SQL语句如何写?
- 表行数相除问题.
- 求一查询语句的写法
- 怎样打开 Visual Studio 的 Object Viewer(对象浏览器)?
- 如果表存在就将其删除
- 一个select 查询语句,头晕了
- 哪里有Sybase的ODBC/JDBC/ADO驱动程序?
- 有请大力等高手:如何计算每日合计,每月合计,本年累计(直接用sql能不能实现,给个思路也行)
- 关于HOST_NAME()的超级怪问题!请专家赐教!急
- 那位朋友SQL2000的存储过程好,能否把我改如下代码变成存储过程里用
FROM users因为不能用iif 应该怎么写法呢
换个提法保留fb数值最小的fa进行计数是否合理?
2、case
select left(ua,case when patindex('%/%',ua) = 0 then len(ua) else patindex('%/%',ua) end)
from users/*第一个问题(测试数据该动了一下,楼主的例子数据好像有矛盾)*/
----创建测试数据
declare @t table(fa int,fb int)
insert @t
select 11 , 3 union all
select 31 , 2 union all
select 21 , 2 union all
select 11 , 3 union all
select 11 , 4
----方法一:效率较高
select fb,count(fb) as fbcount from
(
select fb,fa from @t group by fb,fa
) b group by fb----方法二:效率最差
--生成唯一ID
if object_id('tempdb..#tmp') is not null
drop table #tmp
select id = identity(int,1,1),* into #tmp from @t
--汇总计数
select fb,count(fb) as fbcount from
(
select * from #tmp a
where not exists(select 1 from #tmp where fa = a.fa and fb = a.fb and id < a.id)
) as b
group by fbdrop table #tmp
1 2
3 2
2 3
1 3
--测试代码
declare @t table(fa int,fb int)
insert @t
select 1 ,2
union all
select 3, 2
union all
select 2, 3
union all
select 1, 3
--查询语法:
select fb,count(fa) from
(select fa,min(fb) as fb from @t group by fa)a
group by fb
--结果
fb
----------- -----------
2 2
3 1(所影响的行数为 2 行)