需要分组和计数查询

时间:2010-01-27 06:11:18

标签: sql tsql

假设我有一张包含threadiditemid的表格。 itemid可以有多个条目具有相同的threadid值...

查询:

SELECT DISTINCT 
       THREADID, 
       ITEMID 
  FROM THREADS 
 WHERE THREADID IN (SELECT DISTINCT THREADID FROM THREADS WHERE ITEMID = 10151)

的产率:

THREADID    ITEMID
----------- --------------------
149         10000
149         10076
149         10123
149         10151
149         10225
149         10227
149         10243
149         10245
149         10282
149         10310
149         10311
149         10312
149         10350
2000        10151
2000        10243

如何将其包含在另一个查询中,并按查询顺序获取:

THREADID      ITEMID
------------- ----------
149         13
2000         2

4 个答案:

答案 0 :(得分:1)

你可以尝试

SELECT  sub.THREADID,
        COUNT(1) TOTAL
FROM    (
            SELECT  DISTINCT 
                    t.THREADID, 
                    t.ITEMID 
            FROM    THREADS t INNER JOIN
                    THREADS tt  ON  t.THREADID = tt.THREADID
                                AND tt.ITEMID = 10151
        ) sub
GROUP BY sub.THREADID
ORDER BY sub.THREADID

答案 1 :(得分:1)

使用CTE的SQL Server 2005+:


  WITH threads_cte AS (
    SELECT DISTINCT x.threadid 
      FROM THREADS x
     WHERE x.itemid = ?)
  SELECT t.threadid,
         COUNT(DISTINCT t.itemid) 'num_itemid'
    FROM THREADS t
    JOIN threads_cte tc ON tc.threadid = t.threadid
GROUP BY t.threadid

非CTE等效物:


  SELECT t.threadid,
         COUNT(DISTINCT t.itemid) 'num_itemid'
    FROM THREADS t
    JOIN (SELECT DISTINCT x.threadid 
            FROM THREADS x
           WHERE x.itemid = ?) y ON y.threadid = t.threadid
GROUP BY t.threadid

答案 2 :(得分:0)

with FirstQuery AS 
(
SELECT DISTINCT THREADID, ITEMID FROM THREADS WHERE THREADID IN (SELECT DISTINCT THREADID FROM THREADS WHERE ITEMID = 10151)
)
SELECT THREADID, COUNT(*)
FROM FirstQuery;

答案 3 :(得分:0)

SELECT DISTINCT THREADID, COUNT(ITEMID) AS ITEMS 
FROM THREADS 
WHERE THREADID IN (SELECT DISTINCT THREADID FROM THREADS WHERE ITEMID = 1059)
GROUP BY THREADID
ORDER BY THREADID