簡體   English   中英

更正SQL計數發生次數

[英]Correct SQL count occurrences

有下表:

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   | 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

試試這個

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

如果您只想要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

ps你可以使用第二個查詢而不用VID作為第一個查詢,但它更復雜

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

以下工作,雖然我假設你想要計算每個不同的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
<?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");


}

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM