我使用sql server,我有表:
tbl_GroupUser:
user_id, group_id
这是一个包含用户及其所在组的表(每个组都有多个user_id,每个用户都有多个组)。
tbl_group:
id, name
tbl_User:
id, age,....(information about the user)
tbl_Group的id与group_id之间以及tbl_User的id与user_id之间存在一对多的关系。
我创建了一个查询,返回特定用户只有2个用户的组的百分比,我想要一个返回所有用户结果的查询。这是我的查询:
SELECT cast((SELECT count(*) FROM
(SELECT user_id FROM tbl_GroupUser WHERE group_id in
(SELECT group_id FROM (SELECT t1.group_id, count(distinct t1.user_id) as numberOfUsers
FROM tbl_GroupUser as t1 JOIN tbl_GroupUser as t2 ON t1.group_id = t2.group_id group by
t1.group_id) y WHERE y.numberOfUsers = 2)) as x WHERE x.user_id = 'user') as decimal) * 100 /
(SELECT count(*) FROM tbl_GroupUser WHERE user_id = 'user')
这意味着,计算用户所在的所有组,其中包含2个用户,并将其除以用户所在的组总数。
我想要的一个例子:
tbl_GroupUser:
group_id | user_id
------------------
1 | 1
1 | 2
2 | 1
结果:
user_id | p_Grp2
----------------
1 | 50.0
2 | 100.0
答案 0 :(得分:1)
简单创建用户定义功能并在选择查询中使用
alter function UDF_GetPercentage(@UserId int)
returns decimal(18,10)
as begin
declare @Percentage decimal(18,10)
SELECT @Percentage = cast(
(SELECT count(*) FROM
(SELECT user_id FROM tbl_GroupUser WHERE group_id in
(SELECT group_id FROM (SELECT t1.group_id, count(distinct t1.user_id) as numberOfUsers
FROM tbl_GroupUser as t1 JOIN tbl_GroupUser as t2 ON t1.group_id = t2.group_id group by
t1.group_id) y
WHERE y.numberOfUsers = 2)
)
as x
WHERE x.user_id in (@UserId)
) as decimal)
* 100
/
(SELECT count(*) FROM tbl_GroupUser WHERE user_id in (@UserId ))
return @Percentage
end
并在像这样的选择查询中使用
SELECT user_id, dbo.UDF_GetPercentage(user_id) as p_Grp2
FROM tbl_GroupUser
group by user_id
答案 1 :(得分:-1)
你不是在尝试这么简单吗?
SELECT user_id, 100.0/COUNT(0) as p_Grp
FROM tbl_User u
INNER JOIN tbl_GroupUser gu ON gu.userId = u.Id
GROUP BY user_id;
答案 2 :(得分:-1)
使用窗口功能实时计算组成员,然后按用户聚合数据:
function cancelBtn() {
return (
<Form.Btn type={ this.props.closeBtnType || 'secondary-outline' }
size={ this.props.closeBtnSize || 'lg' }
key="cancelBtn"
onClick={ this.props.closeBtnAction ? this.doCloseAction.bind(this) : this.close.bind(this) }
>{ this.props.closeBtnText || 'Cancel' }</Form.Btn>
);
}