Jump to content

Sum Unique Values of a Column


innitboy

Recommended Posts

I have 3 columns of data

500 -- 150 -- 54
500 -- 150 -- 32
500 -- 148 -- 75
500 -- 132 -- 98

I would like it to display this

1. 500 - 430

The sum of the unique rows in 2nd column (150 + 148 + 132 = 430)

Should I be looking to make 3 different tables from this data and join them or can i get the sum of the 2nd column filtered by the first column in this same table,

Here is some code but its not working

Thanks in advance for any help :)
[code]
$query  = "SELECT id, 1stlevelkey,  FROM  keywords
    where 1stlevelkey = '".$stlevelkey."'
    group by 1stlevelkey  ";
    $result = mysql_query($query);

while ($row = mysql_fetch_assoc($result)) {


    $query  = "SELECT id, 1stlevelkey, 
sum(2ndlevel) / count(2ndlevel)  as count2nd
FROM  keywords
    where 1stlevelkey = '".$firstlevelkey."'
    group by 1stlevelkey  ";
    $result = mysql_query($query);

while ($row = mysql_fetch_assoc($result)) {

print_r($row['1stlevelkey']);
echo "-";
print_r($row['count2nd']);
echo "<br>";
    }
} [/code]
Link to comment
https://forums.phpfreaks.com/topic/34979-sum-unique-values-of-a-column/
Share on other sites

I can get it to return the list grouped by the 2nd column with the code below

like this

500 - 150
500 -- 148
500 -- 132

however i cannot get it to do this

500 - 430
[code]
$query  = "SELECT id, 1stlevelkey,  sum(distinct 2ndlevel) / count(distinct 2ndlevel)  as count2nd
    FROM  keywords
    group by 2ndlevelkey  ";
    $result = mysql_query($query);

while ($row = mysql_fetch_assoc($result)) {

print_r($row['1stlevelkey']);
echo "-";
print_r($row['count2nd']);
echo "<br>";
    } [/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.