我有5列这样的表
+----+-------------------------+-----------+--------+-----------+
| Id | CreateDate | CompanyId | UserId | IsEnabled |
+----+-------------------------+-----------+--------+-----------+
| 1 | 2016-01-02 23:40:46.517 | 1 | 1 | 1 |
| 2 | 2016-01-16 00:07:59.857 | 1 | 2 | 1 |
| 3 | 2016-01-25 15:17:54.420 | 3 | 3 | 1 |
| 25 | 2016-03-07 16:48:39.260 | 24 | 10 | 0 |
| 26 | 2016-03-07 16:48:39.263 | 25 | 2 | 0 |
+----+-------------------------+-----------+--------+-----------+
(感谢http://www.sensefulsolutions.com/2010/10/format-text-as-table.html代表ASCII表!)
我试图检查是否为多个CompanyId记录了UserId。
到目前为止,我设法通过使用此查询检查UserId是否恰好出现多个
WITH T AS
(
SELECT * ,
Count(*) OVER (PARTITION BY UserId) as Cnt
From CompanyUser
)
select Distinct UserId
FROM T
Where Cnt >1
正确返回2.
我遇到的问题是,如何参数化UserId并检查是否为多家公司录制了Id。
答案 0 :(得分:1)
Declare @UserID as bigint
Set @UserID = 2
select Distinct Count(CompanyID)
FROM ComapynUser
Where UserId = @UserId
我认为这可以满足您的需求。