I am writing a script for a car show. Users choose the car number and vote 1-5 on various criteria. There are multiple users voting for the same car, but they can only vote once for each car, I check for this.
Now I have a table of a unique carNumber and 1-5 votes for each criteria, per car.
Here is how I find the total score for each individual users vote
SELECT carNum, exterior+interior+engine AS Score FROM Judge_Votes WHERE catagory = '$catNum' ORDER BY carNum
Reults
CarNum: Score:
18 11
14 8
13 15
12 8
12 11
2 14
I want to add up the total score from each user into a final score result. IE car 12 has 19 total score.
The question I have. How can I find the total score using sql or php?
Just use SUM and ORDER BY:
SELECT carNum, SUM(exterior+interior+engine) AS Score
FROM Judge_Votes
WHERE catagory = '$catNum'
GROUP BY carNum
That should do the "trick"
SELECT carNum, sum(exterior + interior + engine) as Score
FROM Judge_Votes
WHERE gatagory = '$catNum'
GROUP BY carNum
ORDER BY carNum
The following should do the trick I think. The logic is that you group your result per car (GROUP BY carNum) and then use the build in SUM function of SQL.
SELECT SUM(exterior+interior+engine) as totalScore, carNum
FROM Judge_Votes
WHERE catagory = '$catNum'
GROUP BY carNum
ORDER BY carNum;
Related
I've 4 table for a newsletter. Newsletters, Subscribers, Subscriber Groups and Selected Subscriber Groups. I've choose subscriber groups in campaign edit area, and its save selected groups to tbl_newsletter_groups table like;
tbl_newsletters
NID title details
1 text 1 content 1
2 text 2 content 2
tbl_subscriber_groups
GID group_name
5 group 1
6 group 2
tbl_subscribers
SID GID email name
10 5 sub1#mail.com sub1 name
11 6 sub1#mail.com sub1 name
tbl_newsletter_groups
NGID NID GID
15 1 6
16 1 6
17 1 6
I want to show total selected subscriber count when I list newsletters in my page. My soulution works fine, Im looking for simple and clearly statement, there any faster way available like in single newsletter list statement?
Here my own count style (yes I know its too bad and long way);
$subGID = array();
$list = $myconn->query("SELECT * FROM tbl_newsletters");
while($listRs = $list->fetch_assoc()){
$grps = $myconn->query("SELECT * FROM tbl_newsletter_groups WHERE NID=". $listRs['NID'] ."");
while($grpsRs = $grps->fetch_asscoc()){
$subGID[] = $grpsRs['GID'];
} $grps->free();
$subs = implode(" OR GID=",$subGID);
$count = mysqli_num_rows($myconn->query("SELECT ID FROM tbl_subscribers WHERE GID=". $subs));
echo('Total Selected Subscriber: '.$count);
} $list->free();
Thanks.
The search term you want is "set-based logic".
Your thinking is sound: you need everything from tbl_newsletters, then you need to count results from tbl_subscribers, but in order to get those you need information from tbl_newsletter_groups.
In SQL, that's an indication you want a join. You've already discovered the conditions you need, you just don't know the syntax. A reference manual can help there.
Now you'll have a bunch of records, which you need to smash into a smaller number of records. You need aggregation functions and a GROUP BY clause.
So here's the final query:
SELECT n.NID, n.title, n.details, COUNT(s.SID)
FROM tbl_newsletters AS n
JOIN tbl_newsletter_groups AS g ON n.NID = g.NID
JOIN tbl_subscribers AS s ON g.GID = s.GID
GROUP BY n.NID
I've tried everything to figure this out but I can't get the correct total. My attempts either add all the records and not just the latest ones or I only get the first record.
My first table: hubs
hubID hubName
1 hub1
2 hub2
My second table: hub_reports
reportID hubID date health school
1 1 2012-04-27 467 322
2 2 2012-04-23 267 22
3 1 2012-01-20 176 623
So what you see is 2 tables, one with the organizations name and other info and the second with the reports that each organization submits quarterly. I want to list all the organizations and their latest report. At the bottom of the table I want to add all the available health kits and school kits that are currently available.
Here's the code I'm using right now to display all the organizations and their latest reports.
SELECT * FROM (SELECT hubName, date, health, school FROM hub_reports,
hubs WHERE hub_reports.hubID = hubs.hubID ORDER BY date DESC) AS Total
GROUP BY hubName
This seems to work but when I try the same tactic to get the SUM of the health and school columns I don't get the right answer.
SELECT SUM(health) FROM (SELECT hubName, date, health FROM
hub_reports, hubs WHERE hub_reports.hubID = hubs.hubID ORDER BY date
DESC) AS Total GROUP BY hubName
I tried other using a LEFT JOIN approach that I found on another forum but it didn't seem to work any better. But I maybe I wasn't doing it right.
Please help!
I just encountered a similar problem in a project of mine. A variation of this query worked for me. Hope it is helpful to you.
SELECT hubs.hubName, hub_reports.*,
SUM(hub_reports.health) AS ttl_health,
SUM(hub_reports.school) AS ttl_school
FROM hubs, hub_reports
WHERE hub_reports.hubID = hubs.hubID
GROUP BY hub_reports.hubID
ORDER BY hub_reports.date DESC
Here's the PHP:
$rs = mysql_query( 'SELECT hubs.hubName, hub_reports.*,
SUM(hub_reports.health) AS ttl_health,
SUM(hub_reports.school) AS ttl_school
FROM hubs, hub_reports
WHERE hub_reports.hubID = hubs.hubID
GROUP BY hub_reports.hubID
ORDER BY hub_reports.date DESC' );
$grand_total['school']=0;
$grand_total['health']=0;
while ( $row = mysql_fetch_assoc( $rs ) ){ // Step through each hub
echo "{$row['hubName']} shows {$row['ttl_school']} total school, {$row['ttl_health']} total health";
$grand_total['school'] += $row['ttl_school'];
$grand_total['health'] += $row['ttl_health'];
}
echo "Grand Total School: {$grand_total['school']}, Grand Total Health: {$grand_total['health']}";
You're likely looking for the MAX() function.
Try this:
SELECT h.hubID, h.hubname, MAX(hr.date) as hrdate, SUM(hr.health) as health, SUM(hr.school) as school
FROM hubs h
LEFT JOIN hub_reports hr ON hr.hubID = h.hubID
GROUP BY h.hubID
Edit
You want the MAX date so it only returns the most recent entry (assuming your entries are entered by date, of course).
Here is the mySQL I got
id terms
1 a
2 c
3 a
4 b
5 b
6 a
7 a
8 b
9 b
10 b
I want to get an alphabetized list sorted by count as follows
terms count
a 4
b 5
c 1
What mySQL statement do I need for that?
I believe something like this will work:
SELECT terms, COUNT( id) AS count
FROM table
GROUP BY terms
ORDER BY terms DESC
Read : GROUP BY (Transact-SQL)
Groups a selected set of rows into a set of summary rows by the values of one or more columns or expressions in SQL. One row is returned for each group. Aggregate functions in the SELECT clause list provide information about each group instead of individual rows.
You just need to apply group by clause for getting result
select terms, count (id) as count from table
group by terms
order by terms
I had a very similar need for a used record store to display artists in stock alphabetically with their count in parenthesis e.g.:
Smokey Robinson and The Miracles (2) | Sonic Youth (2) | Spoon (3) | Steely Dan (1) | Stevie Wonder (2) | Sufjan Stevens (1) |
Note that I used SELECT DISTINCT when pulling from my table "records". Here are the relevant code snippets:
//QUERY
$arttool = mysql_query("SELECT DISTINCT * FROM records GROUP BY artist ORDER BY artist ASC");
//OUTPUT LOOP START
while($row = mysql_fetch_array($arttool)){
//CAPTURE ARTIST IN CURRENT LOOP POSITION
$current=$row['Artist'];
//CAPTURING THE NUMBER OF ALBUMS IN STOCK BY CURRENT ARTIST
$artcount = mysql_num_rows(mysql_query("SELECT * FROM records WHERE artist = '$current'"));
//ECHO OUT.
echo $current . "($artcount)";
The actual code in my site is more complicated, but this is the bare bones of it. Hope that helps...
Currently I have an sql query which finds the amount of records in the database for a specific person (Ms White), how can I repeat the function for every surname within the table and print them out in a sensible format?
$query = "SELECT COUNT(Surname) FROM Customers WHERE Surname='White'";
GROUP BY I think is what you are looking for
SELECT COUNT(*),Surname FROM Customers GROUP BY Surname
Wouldn't it be better to run just one query with the count per each surname?
select Surname, count(*) as Total from Customers
group by Surname
This will return results like this:
Person Total
White 4
Mustard 2
Plum 1
etc...
Use
SELECT count(1) as "Counter", surname FROM Customers GROUP BY surname
This will give you output like below.
Counter + Surname
++++++++++++++++++++
10 + SN1
15 + SN2
11 + SN3
I've created a game with a highscore table in MySQL.
I have a "My scores" button that needs to retrieve the users scores, e.g.:
10. John 395
42. John 340
90. John 10
How should I go out retrieving the rank (10th, 42th, 90th) of each score of the user?
I could pull all the scores from the database and iterate through them but that doesn't seem like a good solution.
Let me try to expand:
I retrieve all MY scores from the database. E.g. 10 scores. I want to display these 10 scores however I won't know what the rank of these scores is compared to the other scores in my database! (10th, 16th, etc) ..Hope that makes more sense...
Thanks
For the position in the total list you either need to build up a list every time you want this overview, or use a stored procedure to build a list for a given moment. You could 'cache' a list on a given interval. Or maybe update a list when some one played a game that would change the top 100.
As #WhiteElephant suggested, you'd be making the table every time you want the data.
#stefandoorn suggest to not use the optimized count of sql, i think this is not efficient enough for these kind of computations.
A simple SQL query would do it for you. For example, if you want the 10th score, you could use:
SELECT name, score FROM highscores ORDER BY score DESC LIMIT 1 OFFSET 9
The offset will always be the position required - 1.
If you want to have the associated rank as a column beside the score, you could do the following:
SELECT #rownum:=#rownum+1 position, name, score FROM (SELECT #rownum:=0) r, highscores ORDER BY score DESC
This doesn't work with an offset (the position number will always start at 1). The result would be something like the following:
+----------+-------------+-------+
| position | name | score |
+----------+-------------+-------+
| 1 | Player 1 | 27681 |
| 2 | Player 2 | 14982 |
+----------+-------------+-------+
But I think the best solution is to just loop through the returned values with an index and use the index to keep track of the position.
SELECT
id, name, score,(select count(*) FROM highscores AS higherscores WHERE higherscores.score>currentscores.score)+1 AS rank
FROM
highscores AS currentscores
WHERE name="john"
;
Just use ORDER BYscoreDESC in the end of your query to sort them in reversed order (from high to low). When iterating and showing it in PHP you can use a count:
Query e.g.: SELECT * FROM scores ORDER BY score DESC
$count = 1;
$sql = 'SELECT * FROM scores ORDER BY score DESC';
$result = mysql_query($sql) or die(mysql_error());
while($fetch = mysql_fetch_object($result)) {
echo $count . ' ' . $fetch->score . '<br />';
$count++;
}