1

我有下表。

表 A

用户名 | 键
1 | 2
| 乙
3 | 4
| 5
|

表 B

用户名 | 数字
1 | 50
1 | 300
2 |
3 | 100
4 | 20

我有这样的查询

SELECT COUNT(key) AS cnt, key 
FROM A 
WHERE key <> '' 
GROUP BY key 
ORDER BY cnt DESC

结果应该是这样的

关键 | cnt 
A | 2
乙 | 1
℃ | 1

我想补充的是加入表B。
如果UserID在表B中的Num中有值,我想用/Num按键分组计算UserID

这是想要的结果

关键 | cnt | 有数字吗?
一个 | 2 | 2
乙 | 1 | 0
℃ | 1 | 1

我尝试编写子查询,但无法将其附加到主查询。子查询是这样的。

SELECT COUNT(DISTINCT UserID) AS num 
FROM B 
LEFT OUTER JOIN A ON B.UserID = A.UserID 
WHERE Num <>'' AND key <> '' 
GROUP BY key
4

3 回答 3

2

如果我理解正确,那么您要查找的是表 A 中的键被用户 ID 使用时的计数,然后是表 B 中唯一出现在第一个中的用户 ID 的计数表 A 查询并有一个 Num。

试试这个:

SELECT a.[Key], COUNT(a.[Key]) AS cnt, isNull(SUM(b.bCnt), 0) AS [Has Num?]
FROM #TableA a
LEFT OUTER JOIN (
    SELECT b.UserID, 1
    FROM #TableB b
    WHERE LEN(b.Num) > 0
    GROUP BY b.UserID
) b (UserID, bCnt) ON b.UserID = a.UserID
WHERE LEN(a.[Key]) > 0 
GROUP BY a.[Key] 

此查询给出了您所期望的结果。

于 2013-02-20T17:42:24.927 回答
0
DECLARE @TableA TABLE(UserID INT, [Key] CHAR(1))
INSERT INTO @TableA VALUES(1,'A'),(2,'B'),(3,'A'),(4,'C'),(5,'')

DECLARE @TableB TABLE(UserID INT, Num INT NULL)
INSERT INTO @TableB VALUES(1,50),(1,300),(2,NULL),(3,100),(4,20)


SELECT x.[Key],x.Cnt,y.[Has Num?]
FROM 
    (   SELECT [Key],Cnt = COUNT([Key])
        FROM @TableA 
        WHERE LEN([Key])>0
        GROUP BY [Key]
    )X
JOIN
    (
        SELECT a.[Key],[Has Num?] = COUNT(b.Num)
        FROM @TableA a
        JOIN @TableB b ON a.UserID = b.UserID
        GROUP BY a.[Key]
    )Y
ON x.[Key] = Y.[Key]


Key Cnt Has Num?
A   2   3
B   1   0
C   1   1
于 2013-02-20T03:23:19.270 回答
0

外部申请怎么样

SELECT [Key], COUNT(a.[Key]) AS cnt, SUM(x.NumCount) AS [Has Num?]    
FROM @TableA a
OUTER APPLY (SELECT COUNT(NUM) AS NumCount 
             FROM  @TableB b 
             WHERE b.UserId = a.UserId AND Num IS NOT NULL
            ) x
WHERE [Key] <> '' 
GROUP BY [Key]
ORDER BY cnt DESC

结果:

Key  cnt         Has Num?
---- ----------- -----------
A    2           3
B    1           0
C    1           1
于 2013-02-20T06:06:27.877 回答