根据一列计算不同

时间:2014-07-01 16:59:16

标签: sql sql-server

我有下表

ID | AreaPath | IterationPath |

1       Area1     Iteration1
2       Area2     Iteration1
2       Area2     Iteration2

我只想在ID列上使用count。

想要的输出应该是:

CountID | ID | AreaPath | IterationPath |

    1      1    Area1      Iteration1
    2      2    Area2      Iteration1
    2      2    Area2      Iteration2

以下查询:

select 
    count(TRV.ID ) as CountID, 
    TRV.ID,
    TRV.AreaPath, 
    TRV.IterationPath 
FROM table TRV 
Group BY AreaPath, IterationPath 

给我以下输出:

CountID | ID | AreaPath | IterationPath |

    1      1    Area1      Iteration1
    1      2    Area2      Iteration1
    1      2    Area2      Iteration2

如何更改它以获得所需的输出?

1 个答案:

答案 0 :(得分:2)

除了MySQL之外的所有四大数据库:

SELECT  COUNT(*) OVER (PARTITION BY id) cnt,
        m.*
FROM    mytable m

在MySQL中:

SELECT  (
        SELECT  COUNT(*)
        FROM    mytable mi
        WHERE   mi.id = m.id
        ) cnt,
        m.*
FROM    mytable m