我有:
TABLE: USERS
UID | NAME
1 | Bob
2 | John
我有:
TABLE: HITS
HITID | UID
1 | 1
2 | 2
3 | 2
4 | 1
5 | 2
6 | 2
我想:
UID | HITS
1 | 2
2 | 4
看起来很简单,但我似乎做不到?
尝试这个:
SELECT UID, COUNT(UID) HITS FROM HITS
GROUP BY UID;
这可能会帮助你
DECLARE @USERS TABLE(UID INT, NAME VARCHAR(20))
INSERT INTO @USERS (UID,NAME) VALUES ('1','Bob'),('2','John')
DECLARE @HITS TABLE(HITID INT,UID INT)
INSERT INTO @HITS (HITID,UID) VALUES('1','1'),('2','2'),('3','2'),('4','1'),('5','2'),('6','2')
如果要同时使用 USERS 表和 HITS 表,请使用 JOIN
SELECT U.UID,COUNT(H.HITID) AS HITS FROM @USERS AS U INNER JOIN @HITS AS H ON U.UID = H.UID GROUP BY U.UID
或使用简单查询如果您只想使用 HITS 表
SELECT UID, COUNT(UID) HITS FROM @HITS GROUP BY UID
我也在其中创建了临时表。
这可以解决问题
SELECT H.UID, COUNT(*) AS 'HITS'
FROM HITS H
GROUP BY H.UID
SELECT b.UID, COUNT(b.UID) HITS FROM HITS a, USERS b
WHERE a.UID=b.UID
GROUP BY UID
这应该工作
如果你想拥有用户的名字,那么你需要加入它
SELECT a.Name, COUNT(*) totalCount
FROM users a
INNER JOIN HITS b
ON a.UID = b.UID
GROUP BY a.UID