我有以下表格。
表A
UserID | key
1 | A
2 | B
3 | A
4 | C
5 |
表B
UserID | Num
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
结果应该是这样的
key | cnt
A | 2
B | 1
C | 1
我想补充的是加入表B.
如果UserID在表B中的Num中有值,我想用/ Num Grouped by Key计算UserID
这是理想的结果
key | cnt | Has Num?
A | 2 | 2
B | 1 | 0
C | 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
答案 0 :(得分:2)
如果我正确地理解了这一点,你要找的是当用户ID使用它们时表A中键的计数,然后是表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]
此查询提供您期望的结果。
答案 1 :(得分: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
答案 2 :(得分:0)
OUTER APPLY
怎么样?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