更正SQL计数发生次数

时间:2014-04-10 08:58:54

标签: sql sql-server-2008

有下表:

ID | ShopId | GroupID | Vid
1  |   10   |    646  |248237
2  |    5   |    646  |248237
3  |    7   |    646  |248237 
4  |    5   |    700  |248237
5  |    7   |    700  |248237

我想添加一个包含每个GroupId中Vid值的列。类似的东西:

ID | ShopId | GroupID | Vid   | Occurences
1  |   10   |    646  |248237 |      3
2  |    5   |    646  |248237 |      3 
3  |    7   |    646  |248237 |      3
4  |    5   |    700  |248237 |      2 
5  |    7   |    700  |248237 |      2

5 个答案:

答案 0 :(得分:1)

试试这个

    Select ID,ShopId,GroupID,Vid,
    (select count(GroupID) from table_name where GroupID=tb.GroupID) as Occurences
    From table_name as tb

答案 1 :(得分:1)

如果您只想要VID计数而不管它们的值,您可以写

Select *, (select count(1) from table t1 where t1.GroupID = t2.GroupID) Occurences
From table t2

但是如果你想在每个组中计算类似的VID,你可以写

Select table.*, t.cnt as  Occurences
from table
inner join (select count(1) cnt, groupID, VID from table group by groupID, VID) t on t.groupID = table.groupID and t.VID = table.VID

P.S。你可以使用第二个查询而不用VID作为第一个查询分组,但它更复杂

答案 2 :(得分:0)

select t.*, occ.Occurences 
from the_table t join
     (select GroupID, count(*) as Occurences
      from the_table
      group by GroupID) occ ON t.GroupID=occ.GroupID

答案 3 :(得分:0)

以下作品,虽然我假设你想要计算每个不同的GroupID,Vid配对。

 select 
  t.[ID]
, t.[ShopID]
, t.[GroupID]
, t.[Vid]
, cnt
from Table1 t
inner join
  (
    select [GroupID]
          ,[Vid]
          ,cnt = count(*)
    from Table1
    group by [GroupID], [Vid]
  ) a
  on a.GroupID = t.GroupID
  and a.Vid = t.Vid

答案 4 :(得分:0)

<?php
$host='hostname';

$username='username';

$password='password';

$db='db';

$con=mysql_connect($host,$username,$password);

mysql_select_db($db,$con);

mysql_query("ALTER TABLE table_name ADD Occurences Int");

$query=mysql_query("SELECT * FROM table_name");

while($row=mysql_fetch_array($query))

{`

     $group=$row['GroupID'];

    $new_query=mysql_query("SELECT * FROM table_name WHERE GroupID = $group ");

    $count=mysql_num_rows($new_query);

    $update_query=mysql_query("UPDATE table_name SET Occurences=$count WHERE GroupID=$group");


}

?>