如何使用具有子查询的内部联接的distinct

时间:2011-03-22 07:10:46

标签: c# asp.net sql-server-2008

我希望事务表中的UserId应该是不同的,所以请你告诉我如何从具有内部联接的事务表中获得不同的userid?

SELECT     TransactionMaster.TransId, TransactionMaster.UserId, TransactionMaster.SessionId, TransactionMaster.TotalAmount, TransactionMaster.PaymentStatus, 
                      TransactionMaster.TransDate, TransactionMaster.ShippingId, TransactionMaster.IPAddress, TransactionMaster.IsShipped, TransactionMaster.DeliveredDate, 
                      Register.ID, Register.Password, Register.FirstName, Register.LastName, Register.MiddleName, Register.Address, Register.CountryId, Register.StateId, 
                      Register.CityId, Register.Email, Register.Status, Register.IPAddress AS Expr1, Register.Account, Register.ZipCode
FROM         TransactionMaster INNER JOIN
                      Register ON TransactionMaster.UserId = Register.ID
WHERE(TransactionMaster.UserId IN (SELECT Distinct UserId FROM TransactionMaster WHERE TransactionMaster.UserId IN(SELECT  UserId FROM TransactionMaster)))

现在我得到了输出:

**Transid                              UserId        sessioId            otherfields**

Ai36Lft9X4PrHg8p7BTs2n5K5Dcz4E        z8CFj92M     dzwsyf55s1io1e552ifty555
d3YAs6j4L2SxJm95PeDn78NbCq49By        f4M5Rmr9     1u0mkd45rt5jz455axcvbgbd
k6Z5LiYp39CnBs24Gca8D7Sfw8J6Xd        f4M5Rmr9     zo1gwz45gtbg3uegkkf21dmz

但我想要这种类型的输出

**Transid                                  UserId        sessioId       otherfields**

Ai36Lft9X4PrHg8p7BTs2n5K5Dcz4E        z8CFj92M     dzwsyf55s1io1e552ifty555
d3YAs6j4L2SxJm95PeDn78NbCq49By        f4M5Rmr9     1u0mkd45rt5jz455axcvbgbd

3 个答案:

答案 0 :(得分:2)

您可以使用cterow_number()来获取不同的用户ID。 这是一个简化版本,您应该可以应用于更复杂的查询。

declare @T table(TransID varchar(50), UserID varchar(8), SessionID varchar(50))

insert into @T values
('Ai36Lft9X4PrHg8p7BTs2n5K5Dcz4E',        'z8CFj92M',     'dzwsyf55s1io1e552ifty555'),
('d3YAs6j4L2SxJm95PeDn78NbCq49By',        'f4M5Rmr9',     '1u0mkd45rt5jz455axcvbgbd'),
('k6Z5LiYp39CnBs24Gca8D7Sfw8J6Xd',        'f4M5Rmr9',     'zo1gwz45gtbg3uegkkf21dmz')

;with cte as
(
  select
    *,
    row_number() over(partition by UserID order by SessionID) as rn
  from @T
)
select *
from cte
where rn = 1

结果

TransID                        UserID   SessionID                rn
d3YAs6j4L2SxJm95PeDn78NbCq49By f4M5Rmr9 1u0mkd45rt5jz455axcvbgbd 1
Ai36Lft9X4PrHg8p7BTs2n5K5Dcz4E z8CFj92M dzwsyf55s1io1e552ifty555 1

答案 1 :(得分:1)

按UserId分组并确定哪个聚合适用于其余列。我认为这可能会变得很难......

您的问题是,不同的选择始终适用于所有列。因此,您唯一的方法是进行分组,但拥有一个组要求您在要显示的每个列上都有一个聚合函数。如果可行的话,你提供了很少的关于你想要了解的信息。

答案 2 :(得分:0)

首先将即将出现的输出存储在临时表(#TempTrans)中,然后执行以下操作:

SELECT DISTINCT UserID FROM #TempTrans