SQL Server:基于两列返回特殊计数列

时间:2014-03-19 20:17:18

标签: sql sql-server

我想抓住每个“ID”中包含的“代码”的数量。考虑一下这个我想要的表:

╔════════╦════════╦══════╗
║   ID   ║  Code  ║ Count║
╠════════╬════════╬══════╣
║    111 ║ abcd   ║ 2    ║
║    111 ║ abcdes ║ 2    ║
║    222 ║ dddd   ║ 1    ║
║    333 ║ ddww1  ║ 3    ║
║    333 ║ ddww2  ║ 3    ║
║    333 ║ ddww3  ║ 3    ║
║    444 ║ abcde1 ║ 2    ║
║    444 ║ abcde2 ║ 2    ║
╚════════╩════════╩══════╝

如您所见,它返回每个ID中的代码数。

我在想这样的事情......但它不起作用:

SELECT COUNT(CODE) AS CODE_COUNT FROM TABLE1 a, TABLE1 b WHERE a.ID=b.ID;

1 个答案:

答案 0 :(得分:1)

SQL Fiddle

MS SQL Server 2008架构设置

CREATE TABLE TABLE1( ID INT,Code VARCHAR(20))
GO
INSERT INTO TABLE1 VALUES

(111,'abcd'),
(111,'abcdes'),
(222,'dddd'),
(333,'ddww1'),
(333,'ddww2'),
(333,'ddww3'),
(444,'abcde1'),
(444,'abcde2')

查询1

SELECT A.ID
      ,A.Code 
      ,Sub.CODE_COUNT
FROM TABLE1 A
 INNER JOIN (
             SELECT ID , COUNT(*)  AS CODE_COUNT 
             FROM TABLE1
             GROUP BY ID) Sub
ON A.ID = Sub.ID

<强> Results

|  ID |   CODE | CODE_COUNT |
|-----|--------|------------|
| 111 |   abcd |          2 |
| 111 | abcdes |          2 |
| 222 |   dddd |          1 |
| 333 |  ddww1 |          3 |
| 333 |  ddww2 |          3 |
| 333 |  ddww3 |          3 |
| 444 | abcde1 |          2 |
| 444 | abcde2 |          2 |