2014-04-10 25 views
0

以下为表:正确的SQL计数OCCURENCES

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 

回答

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分组作为第一个查询,但它更复杂

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 
1

试试这个

Select ID,ShopId,GroupID,Vid, 
    (select count(GroupID) from table_name where GroupID=tb.GroupID) as Occurences 
    From table_name as tb 
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 
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"); 


} 

?>