求高难SQL语句或解决方法

felix3118 2010-10-25 09:12:42
求高难SQL语句或解决方法

现有一表,是多个用房的记录。例如

姓名 记录A 记录B
张三 1 1
李四 1 0
张三 2 0
李四 2 1
王五 3 1

现在要求得到:
用户记录A相同,记录B不同的比率?

如上,张三,李四的条数为2,比率为100%?

这用sql能得到吗?如不能用代码如何快速实现?
...全文
92 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
sql_lover 2010-10-25
  • 打赏
  • 举报
回复
/*================================
Author:sql_lover
Date:2010-10-25 10:26:29.953
Function:
=================================*/

/*Create Tables*/
create table hotel_count (name varchar(30),id1 int,id2 int)

insert into hotel_count
select '张三', 1, 1 union all
select '李四', 1, 0 union all
select '张三', 2, 0 union all
select '张三', 3, 0 union all
select '李四', 2, 1 union all
select '李四', 3, 1 union all
select '王五', 3, 1

/*How To*/
create view view_hotel_count as
select *,ROW_NUMBER()over(order by name) as serial_num from hotel_count

create proc pro_find_pbt @id1 int as
begin
declare @n1 int
declare @n2 int
declare @f1 float
select @n1=COUNT(1) from view_hotel_count a,view_hotel_count b where a.id1=b.id1 and b.id1=@id1 and a.serial_num<>b.serial_num
select @n2=COUNT(1) from view_hotel_count a,view_hotel_count b where a.id1=b.id1 and b.id1=@id1 and a.serial_num<>b.serial_num and a.id2<>b.id2
if @n1 >0
select CAST(@n2 as float)/CAST(@n1 as float) as probability
end

/*Test*/
exec pro_find_pbt 3

/*Result*/
/*================================
probability
----------------------
0.666666666666667

(1 行受影响)
=================================*/
SQLCenter 2010-10-25
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 yufan27209 的回复:]

比如有人玩足球亚盘,统计不同用户同一场比赛投注相反的概览。
[/Quote]

那应该这么算

--> 测试数据:#
if object_id('tempdb.dbo.#') is not null drop table #
create table #(姓名 varchar(8), 记录A int, 记录B int)
insert into #
select '张三', 1, 1 union all
select '李四', 1, 0 union all
select '张三', 2, 0 union all
select '李四', 2, 1 union all
select '王五', 3, 1

select 记录A, 记录B, count(1)投注 from # group by 记录A, 记录B

/*
记录A 记录B 投注 -- 这里应该是sum(金额)
----------- ----------- -----------
1 0 1
2 0 1
1 1 1
2 1 1
3 1 1
*/
felix3118 2010-10-25
  • 打赏
  • 举报
回复
比如有人玩足球亚盘,统计不同用户同一场比赛投注相反的概览。
shizheyangde 2010-10-25
  • 打赏
  • 举报
回复
还是没明白
felix3118 2010-10-25
  • 打赏
  • 举报
回复
姓名 记录A 记录B
张三 1 1
李四 1 0
张三 2 0
张三 3 0
李四 2 1
李四 3 1
王五 3 1

就是两两比较,找到条数大于20,比率大于80%的记录。
sql_lover 2010-10-25
  • 打赏
  • 举报
回复
同问~~~~~~~~~~
「已注销」 2010-10-25
  • 打赏
  • 举报
回复
写出你想要的结果。
如果出现下面这样的,结果是多少?
张三 1 1
张三 2 0
张三 3 0
SQLCenter 2010-10-25
  • 打赏
  • 举报
回复
需求不清晰,100个人怎么比,两两不同?

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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