我有这个SQL Server查询,它返回每个组的所有组成员。但我想确定每个组成员是否至少有一个“活动”设备。为此,我使用Row_Number并对groupID和memberID进行分区,并通过'Active'列进行排序,该列是BIT类型。 以下查询的结果是正确的。但我只使用数据子集。我读过,因为有点列不是数字,你不应该按它排序。它会产生不可预测的结果。
如何将BIT列转换为INT并在ROW_NUMBER函数中使用它?
这是查询:
WITH OrderedGroupMembers AS
(
SELECT g.GroupID AS GroupID, gm.RecipientID AS MemberID, r.RecipientName AS MemberName, d.Active AS ActiveDevice,
ROW_NUMBER() OVER(PARTITION BY g.GroupID, gm.RecipientID ORDER BY d.Active DESC) AS RowNumber
FROM PagingToolGroups g JOIN PagingToolGroupMembers gm ON g.GroupID = gm.GroupID
JOIN PagingToolRecipients r ON r.RecipientID = gm.RecipientID
JOIN PagingToolDevices d ON d.RecipientID = gm.RecipientID
WHERE g.GroupCreatorID = 'ge39se35'
)
SELECT GroupID, MemberID, MemberName, ActiveDevice
FROM OrderedGroupMembers
WHERE RowNumber = 1
感谢。
更新 这是我的新查询,但我想知道是否有更有效的方法...
WITH OrderedGroupMembers AS
(
SELECT GroupID, MemberID, MemberName, ActiveDevice,
ROW_NUMBER() OVER(PARTITION BY GroupID, MemberID ORDER BY ActiveDevice DESC) AS RowNumber
FROM (
SELECT g.GroupID AS GroupID, gm.RecipientID AS MemberID, r.RecipientName AS MemberName, CAST(d.Active AS INT) ActiveDevice
FROM PagingToolGroups g JOIN PagingToolGroupMembers gm ON g.GroupID = gm.GroupID
JOIN PagingToolRecipients r ON r.RecipientID = gm.RecipientID
JOIN PagingToolDevices d ON d.RecipientID = gm.RecipientID
WHERE g.GroupCreatorID = 'ge35s39'
) AS ActiveAsNum
)
SELECT GroupID, MemberID, MemberName, ActiveDevice
FROM OrderedGroupMembers
WHERE RowNumber = 1
答案 0 :(得分:0)
位类型没有问题。您可以按位类型排序任何其他类型。使用位的一个限制是您不能在一个上聚合,但在这种情况下您可以将其转换为任何数字类型。但事实并非如此,所以您只需按活动列排序即可。这是合法的,不应该有任何问题。