2

我有:

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

看起来很简单,但我似乎做不到?

4

5 回答 5

4

尝试这个:

SELECT UID, COUNT(UID) HITS FROM HITS 
GROUP BY UID;
于 2012-11-23T06:10:11.547 回答
2

这可能会帮助你

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 

我也在其中创建了临时表。

于 2012-11-23T06:25:23.423 回答
1

这可以解决问题

SELECT H.UID, COUNT(*) AS 'HITS'
FROM HITS H
GROUP BY H.UID
于 2012-11-23T06:23:14.203 回答
1
SELECT b.UID, COUNT(b.UID) HITS FROM HITS a, USERS b
WHERE a.UID=b.UID
GROUP BY UID 

这应该工作

于 2012-11-23T06:12:57.790 回答
0

如果你想拥有用户的名字,那么你需要加入它

SELECT  a.Name, COUNT(*) totalCount
FROM    users a
        INNER JOIN HITS b
            ON a.UID = b.UID
GROUP BY a.UID
于 2012-11-23T06:17:06.460 回答