简体   繁体   中英

Correct SQL count occurrences

Having the following table:

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

I want to add a column that contains the number of Vid values in each GroupId. Something like:

ID | ShopId | GroupID | Vid   | Occurrences
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

Try This one

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

if you only want the VID counts no matter their value you can write

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

But if you want the the count of Similar VIDs in each group you can write

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

ps You can use the second query without grouping by VID as first one too but it is more complicated

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

The following works, though I've assumed you want a count for each distinct GroupID, Vid pairing.

 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
<?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");


}

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM