如何将DISTINCT列的重复行数作为另一列?

时间:2013-05-15 10:39:24

标签: sql sql-server-2008

如何制作以下栏目

------------
MakeDistinct
------------
CAT
CAT
CAT
DOG
DOG
PIN
PIN
PIN
PIN

如下所示

-------------   -------
AfterDistinct   Count
-------------   -------
CAT              3
DOG              2
PIN              4

3 个答案:

答案 0 :(得分:3)

通过使用COUNT()子句对MakeDistinct列进行分组,使用GROUP BY功能。

  SELECT MakeDistinct AS AfterDistinct
       , COUNT(MakeDistinct) AS Count
    FROM MyTable
GROUP BY MakeDistinct

输出:

╔═══════════════╦═══════╗
║ AFTERDISTINCT ║ COUNT ║
╠═══════════════╬═══════╣
║ CAT           ║     3 ║
║ DOG           ║     2 ║
║ PIN           ║     4 ║
╚═══════════════╩═══════╝

See this SQLFiddle

答案 1 :(得分:0)

请尝试:

select 
    MakeDistinct AfterDistinct, 
    COUNT(*) [Count] 
from 
    YourTable
group by MakeDistinct

答案 2 :(得分:0)

SELECT MakeDistinct AS AfterDistinct, COUNT(*) AS [COUNT] FROM tablename 
GROUP BY MakeDistinct