Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    MYSQL


SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





Using A Single Sql Statement To Group And Count The Groups


I'm trying to count the total number of items in a table that are grouped e.g. my table is a shopping basket and is like this:

basketID||orderID||productID||quantity
1||1||2||1
2||1||3||1
3||1||4||1
4||2||2||1
5||2||4||1
6||3||4||1

so product 4 appears 3 times, product 2 appears twice and product 3 appears just once

how do use an sql statement (if it is possible) to group the products then list them in the order of which appears most

so i could say

SELECT * FROM basket GROUP BY productID;

and that would group them for me, but i want them listed like

productID
4
2
3

(as 4 has the most occurances, then 2, then 3)




View Complete Forum Thread with Replies

Related Forum Messages:
Group Of Groups
Basically, I have a simple group query...
SELECT `StudentID`, COUNT(*) FROM `StudentHistoryT` GROUP BY `StudentID`

The query returns the number of records for each student.

What I want is a query that produces a count of the number of students with a distinct number of records, that is, I want to group by COUNT(*) and return the COUNT(*) of the new group.

My nieve atmysqlt...
SELECT `StudentID`, COUNT(*) FROM `StudentHistoryT` GROUP BY `StudentID` GROUP BY COUNT(*)

View Replies !
Order Per "Group By" Groups
a table example:

Code:

ID | USER | VALUE |

1 | mike | 8
2 | mike | 10
3 |mike | 12
4 | john | 10
5 | john | 12
6 | john | 15

Desired result grouped by USER:

ID | USER | VALUE |
6 | john | 15
3 | mike | 12

as you can see, I'm ordering the group result by the last value of ID column for each user, then order by user name.

In other words, I need to retrieve the max ID value for each user. also order the result by user name.

How can I do that ?

Myabe there's no need of grouping,

View Replies !
Group All Numbers To A Single Column
I am trying to display an alphabetical list menu bar, by getting the first character of a title, then grouping and counting, so the output would be something like:

A (2)
B (32)
C (7)

...etc

My problem occurs when I have a number as the first character of some titles:

1 (2)
4 (12)
A (2)
B (32)
C (7)

...so basically I am trying to group all the numbers together under #, like:

# (14)
A (2)
B (32)
C (7)

Any ideas how this can be done?

View Replies !
GROUP BY On Single Field Table
I've decided to start logging the searches performed on my site so I can provide better search results, to do this I have put a simple insert query into my search processing script that writes the search into a single field table in my database.
I'm currently viewing this as a long list- not particularly useful - and have caught wind of the GROUP BY function which i'm hoping to use to give myself a useable summary of the searches performed.
Is it possible to use this on a single field table and get meaningful data? The actual function is working fine (basically eliminating duplicate searches) but I need to display the number of searches that each group represents as well.

View Replies !
Elt Command - Extracting Single Item From Group From Field
I have a varchar field which contains a comma delimeted set of data. I
am trying to us the ELT function to extract the first part of the group.
Problem is, ELT does not seem to work when the data comes from a field.
If I take the data and do,

select elt(1,"red","green","blue")
RESULT would be "red"

But if the data was stored in a field (called group) and I did:

select elt(1,group)
RESULT would be red,green,blue

Why is this a problem? I am running mysql 4.1.0 on windows. I am going
to try this on another / older / newer version of a DB today and see if
I can replicate the problem. Wandering if this is a bug or not?

Also, does anyone know if there is a function that compares sets
together. Similar to find_in_set, except both the needle and the
haystack are sets.

View Replies !
Calculate Percentage In A Single Sql Statement
i am trying to calculate percentage of student came to computer laboratory in a single sql statement but no luck.

SELECT f.facultyInitial, COUNT(*) AS TOTAL
FROM attendance att
INNER JOIN academic a
ON att.academicNo = a.academicNo
INNER JOIN program p
ON a.programId = p.programId
INNER JOIN faculty f
ON p.facultyId = f.facultyId
WHERE YEAR(att.attendanceDate) = 񟭆'
GROUP BY f.facultyInitial
ORDER BY f.facultyInitial
alright, sql statement above will produce an output like below:

facultyInitial | TOTAL
---------------------
Account | 2
Civil | 1
FITQS | 3

what i want to do is, to put a percentage at the right side of the TOTAL column.

facultyInitial | TOTAL | PERCENTAGE
-----------------------------------
Account | 2 |
Civil | 1 |
FITQS | 3 |

here is my example to produce a percentage but it does not work

SELECT f.facultyInitial, COUNT(*) AS TOTAL, ROUND(COUNT(att.attendanceId)/TEMP.TOTAL_ROWS * 100, 2))
FROM attendance att
INNER JOIN academic a
ON att.academicNo = a.academicNo
INNER JOIN program p
ON a.programId = p.programId
INNER JOIN faculty f
ON p.facultyId = f.facultyId,
(SELECT COUNT(*) AS TOTAL_ROWS
FROM attendance TEMP
WHERE YEAR(att.attendanceDate) = 񟭆')
WHERE YEAR(att.attendanceDate) = 񟭆'
GROUP BY f.facultyInitial
ORDER BY f.facultyInitial

View Replies !
How Do I Select Data From Two Tables In A Single Statement?
This is a very basic question. I have two tables, say "users" and "purchases":

purchases: order_id, order_user_id, items, date
users: user_id, username, email

What I want to accomplish is to compose a single query that will include the user data along with the purchase information. Something like:

SELECT order_id, order_user_id, items FROM purchases WHERE date = 3/12/09

and then translate the order_user_id into user data, so that I would get a final result of an array of rows where each row would include:

order_id, username, email, items

Is this accomplished by a JOIN statement and how is the result code written (PHP).

View Replies !
Mysql Sql Access 2 Servers In Single Statement
Is it possble to access databases in 2 server simultaneously in sql using the mysql client?

I can use sql to access multiple dabases on the same host1 server when I run 'mysql -h host1' but I cannot find a syntax to access databases on another server, which is supported on other db software.

View Replies !
Need Single COUNT Value For Complex Query
I have a moderately complex query and I want to page the results, limiting to 50 on a page. I know that in order to do so, I need to know the total number of records so that I know whether there are more records remaining so I can show a 'NEXT PAGE' link.

I'm having trouble constructing a COUNT query from my original query because the query accesses 4 tables, two of which are many-to-one association tables. Here is the original query, without a LIMIT clause:

View Replies !
Performance Between Multiple INSERT Statements Vs Single Statement With Lots Of Data
$sql1 = "INSERT INTO mytable VALUES ("zzz","xxx")";
$result = mysql_query ($sql1);
...
$sql1000 = "INSERT INTO mytable VALUES ("zzz1000","xxx1000")";
$result = mysql_query ($sql1000);
vs

$sql = "INSERT INTO mytable VALUES
("zzz","xxx"),
...
("zzz1000","xxx1000")";
$result = mysql_query ($sql);

is there any performance difference between the 2?

btw, there could 1000-5000 row inserts.

View Replies !
Group By And IF Statement
I am attempting to get a simple query working:

select *,MAX(a.teaching_date) as max, MIN(a.teaching_date) as min from teaching a, topic_cat b where a.teaching_topic = b.topic_id or a.teaching_topic = 999 group by a.teaching_topic order by a.teaching_date DESC

This all works, except I don't want to 'group by a.teaching_topic' if a.teaching_topic = 999.

View Replies !
SQL Statement - GROUP BY, MAX()
Can anyone help with writing a SQL query?

A single table RESULTS_RES
Fields: id_res, iduser_res, timestamp_res

Sample data:
1, 1, 2005-01-01
2, 2, 2005-01-01
3, 1, 2005-01-02
4, 1, 2005-01-03
5, 2, 2005-01-03

So basically, 2 users have inserted records several times. User 1 has 3 inserts and user 2 has 2 inserts. What I need is a recordset that displays each user only once with their most recent timestamp - along with the id_res. So, my recordset should look like this:
4, 1, 2005-01-03
5, 2, 2005-01-03

I'm guessing I need some kind of GROUP BY and MAX() statements going on, but not sure how to write this. I keep getting the max date with the wrong matching id_res with this:

SELECT id_res, iduser_res, max(timestamp_res) AS timestamp_res
FROM results_res
GROUP BY iduser_res

That gets me the wrong id_res, like this:
1, 1, 2005-01-03
3, 2, 2005-01-03

Any ideas?

View Replies !
Group By Count
I'm sorta having a small problem here I'm trying to do this query:

SELECT count(*) as result ,tickets_name FROM tickets_tickets t group by tickets_name having count(*) > (avg of the count(*));

and that at the end is just explaining what i want since i haven't been able to get it right so far i tried tried to use two aggregates in a row but that gives me and error or placing a sub-query there.What i want in words would be to get the names and the count of the people that have placed more tickets than the avg. Thank ahead for any info.

View Replies !
Count And Group By ?
I'm working on a blogging site and the customer wants to display the "Top 5 Bloggers". The following two tables store the data and as you would guess the blog table stores the blog and blog_comments stores the comments.

I can run 2 queries grouped by user_id to get the user count then write application code to process the results but would much prefer (for performance reasons) to handle this with SQL.

Is there a pure SQL way to get a combined count of users from both tables?

blog
-------
blog_id
title
content
user_id

blog_comment
------------
blog_id
comment_id
content
user_id

View Replies !
Count And Group
I'm working on a blogging site and one of the customer requirements is to display the "Top 5 Bloggers". Meaning a list of the 5 most active users.

Following are the tables and as you would guess the BLOG table stores blog data and BLOG_COMMENT stores comments/replies to a blog.

Question: Is there a pure SQL approach to get a collective count of users from both tables?

I can achieve this with 2 queries then process the results with application code but would much rather do it with one SQL statement (if possible)

blog
--------
blog_id
title
content
user_id

blog_comment
-------------
blog_id
comment_id
content
user_id

View Replies !
Using Count(xxx) In Where While Using Group By
I have the following query which runs fine but the problem is when I try to only return results where COUNT(ET_ID)>2 I get the error "#1111 - Invalid use of group function ". Is there a different way to be able to do this?

Current working query
-------------------------------
SELECT COUNT(ET_ID) AS TotTickets,
ET_InternalSection
FROM ET
WHERE ET_EventID=1837
AND ET_Status='Available'
AND ET_PriceLevelID=2462
GROUP BY ET_InternalSection
ORDER BY ET_InternalSection ASC

New Query I am trying to run
------------------------------------
SELECT COUNT(ET_ID) AS TotTickets,
ET_InternalSection
FROM ET
WHERE ET_EventID=1837
AND ET_Status='Available'
AND ET_PriceLevelID=2462
AND COUNT(ET_ID)>2
GROUP BY ET_InternalSection
ORDER BY ET_InternalSection ASC

View Replies !
Count On Group
Was wondering if comebody could help me out with a count that i am wanting to do , this is the query that i am doing and its working fine for getting the info that i want.

$result = $DB->query( "SELECT name, UNIX_TIMESTAMP(date), AVG(speed) AS avg_speed, COUNT(*) AS number FROM readings group BY name ORDER BY avg_speed desc LIMIT $maxshow");
while(list($name, $date3, $speed, $count ) = mysql_fetch_row($result))

, what i also want to do is return a count of how many different hosts there are , i am returning the full count of all of them combined but i need something to reflect how many hosts , ie there is a count of 468 total tests taken but out of that there might be only say 30 different hosts that were tested.

View Replies !
Count And GROUP BY
I have worked out the following query and it tested fine using phpmyadmin..

SELECT uset, COUNT(*) FROM user WHERE society = '$society' GROUP BY uset

The problem I have is displaying the results. In phpmyadmin the groups are displayed with the count of each, but I have no idea how I would display the results in php.

View Replies !
How To Count When Using Group By
How can I count the number of rows that match a criteria when using group by? If I just do something like ...

View Replies !
Possibly Wrong Group By Statement?
adspaces
textlinks (linked to adspaces via adspace_id)
shoppingkart (linked to adspaces via item)

Now what I want to do is calculate my database's integrity. That is I want to retrieve the number of textlinks for each adspace and the number of shoppingkart entries for each adspace.

SELECT a.adspots, count(t.id) as current_sold, count(s.id) as in_cart,a.current_available, a.idv11, a.title
FROM `ll_adspace` as a
INNER JOIN `ll_shoppingcart` as s ON (s.item = a.id)
INNER JOIN`ll_textlink` AS t ON (t.adspace = a.id)
GROUP BY a.id

However, I get completely wrong results...possibly a wrong join or group by statement? The results for current_sold and in_cart are way too high.

View Replies !
Using Group By Date And Count
Is there a way to select count(*) by grouping by date, and having multiple
date ranges?

combining...

select field,count(*) from table where datefield > 2004/1/1 and datefield <
2004/1/31
and
select field,count(*) from table where datefield > 2004/2/1 and datefield <
2004/2/29
so that the output is

field 34
field 40

View Replies !
GROUP, UNION And COUNT...
writing a query to create a tree menu, it pulls from a table of music "tracks". In this database there are four "sub_genre" fields for each track, and I need to create a list of all used sub_genres and how many tracks are in each.

The list will look like this:
Expand|Select|Wrap|Line Numbers

View Replies !
Count Function & Group By
Getting an error saying I cannot Group on JState2

Is this a version issue? What is an alternate?
(want to show only results having greater than 2 of the same JState 's)

SELECT COUNT(JState) as JState2, JID, StateTerm
FROM JPosts2, State
WHERE State.StateAbbr=JPosts2.JState AND (`JClass` = 'Mechanics')
GROUP BY JState2 HAVING JState2 >4
ORDER BY JState

View Replies !
Multiple COUNT() And GROUP BY
I think I'm on the right track, but I could use some help. I have a simple database with one table that contains observations of animal behavior. Columns include date, time, and animal_type.
I want an output that shows the number of times each animal type was observed, grouped by date. Something like this (sorry about the formatting)

date cat dog mouse
2004-1-1 1 2 3
2004-1-2 2 3 5
2004-1-3 1 2 3

I've gotten as far as getting one column, which would be this query:
"select date, count(date) as cat from observations group by date"
Can any one tell me how to get the rest?

View Replies !
Count A GROUP BY Result
I'm trying to count the result of a GROUP BY query without using the php mysql_num_rows() function. Is this even possible?

View Replies !
Conditional COUNT() With GROUP BY
creating conditional COUNT statements.

This is the query that works:

SELECT COUNT(color='red' or NULL) as color_red FROM object;

However I need to do a count based on more than one property like this:

SELECT COUNT(color='red' AND state='solid') as red_solid_object FROM object;

View Replies !
Group By And Order By Using Count
I am having real problems with a query. I would usually solve this by doing one query and then another query based on the first to do the final sort (probably cheating!). I know how to do this in coldfusion, but not php.

People have told me it is possible to do what i am after but none of their suggestions have worked so far (on another forum).

Basically, I am grouping on a username and then counting the number of referrals that user has. I want to then order by, descending, the number of referrals, so the person with the most referrals comes at the top.

Query syntax tried so far is here:

SELECT user_1.username, Count(user.refid) AS CountOfrefid
FROM [user] LEFT JOIN [user] AS user_1 ON user.refid = user_1.userid
GROUP BY user_1.username order by Count(user.refid);

and

SELECT user_1.username, Count(user.refid) AS CountOfrefid
FROM [user] LEFT JOIN [user] AS user_1 ON user.refid = user_1.userid
GROUP BY user_1.username order by CountOfrefid;

and

SELECT user_1.username, Count(user.refid) AS CountOfrefid
FROM [user] LEFT JOIN [user] AS user_1 ON user.refid = user_1.userid
GROUP BY user_1.username order by 2;

and

SELECT distinct(user_1.username), Count(user.refid) AS CountOfrefid
FROM [user] LEFT JOIN [user] AS user_1 ON user.refid = user_1.userid
GROUP BY user_1.username order by 2;

View Replies !
Count Using Subquery/group By/etc?
I have a database witha table of jobs and a table of advertisers. Jobs can be assigned an advertiser from which they came, via the advertiser_id.

So what I want to do is get my result list of advertisers with a count of how many jobs for each one.

My advertisers table looks like this:

CREATE TABLE `advertiser` (
`advertiser_id` mediumint(2) unsigned NOT NULL auto_increment,
`advertiser_nicename` varchar(127) collate latin1_general_ci NOT NULL,
`advertiser_name` varchar(127) collate latin1_general_ci NOT NULL,
`advertiser_publisher` varchar(31) collate latin1_general_ci default NULL,
PRIMARY KEY (`advertiser_id`)
);
(I'm not going to normalize advertiser_publisher. :P )

And I'll just say that the jobs table looks like this for simplicity:

CREATE TABLE `jobs` (
`job_id` int(10) unsigned NOT NULL auto_increment,
`advertiser_id` mediumint(2) unsigned NULL,
PRIMARY KEY (`job_id`)
);
So I have my list of advertisers generated as such:

PHP

$advertisers = $DB->get_results( "SELECT * FROM `advertiser` ORDER BY `advertiser_publisher`, `advertiser_name` ASC" );

And I could be very silly and add a count such as this:

PHP

foreach ( $advertisers as $id => $advertiser ) { $advertisers[$id]->advertiser_jobs_count = $DB->get_results( "SELECT COUNT(advertiser_id) FROM `jobs` WHERE `advertiser_id` = $advertiser->advertiser_id", 'NUM', FALSE, TRUE ); }

(Ok dont worry about all the php in there, i think its fairly self explanatory what is going on. )

So obviously I don't want to do that because its totally ridiculous and I'm sure that there would be an sql only method of doing it.

View Replies !
Group By And Count, Point
data in myTable

(id) category point
(1) 1 5
(3) 2 A
(4) 2 3
(5) 2 1
(6) 1 B
I have data in myTable like the above.

The following codes produce the following results.

code1

select sum(point) as point, count(*) as count
from myTable
where category=2

result1

point count
4 3

code2

select id, sum(point) as point, count(*) as count
from myTable
where category=2
group by id
order by id desc

result2

{id) point count
(5) 1 1
I like to produce my target result below.


target result

(id) point count

(5) 4 3

View Replies !
COUNT() Items In Group
I want to GROUP BY a field named 'type' in my database, and find out the total number of rows for each type. How do I achieve this in a single query?

As an example of what I mean in case I didn't make it clear enough. Imagine this is the table...

Code:
TypeValue
dogdata
dogdata
catdata
dogdata
catdata
frogdata
The query should return...

dog = 3
cat = 2
frog = 1

View Replies !
COUNT(*) Problem With GROUP BY
What I'm trying todo is count the total amount of rows that match a series of tags that are related to one or more user_ids.

I've noticed that the COUNT(*) operation returns the total amount of rows that were calculated for each group by label.

so:

lets say that a user_id of 2 belongs to users_tags both in a record where the tag_id is 1 and 2.

SELECT user_id FROM users_tags WHERE tag_id IN (1,2)

I'm therefore going to end up getting two results.

SELECT user_id FROM users_tags WHERE tag_id IN (1,2) GROUP BY user_id.

Ok now I have 1 record (that's what I want), but when I run the count operation I get:

SELECT count(*) FROM users_tags WHERE tag_id IN (1,2) LIMIT 1

which gives me a value of two.

Now lets say that user_id of 3 also belongs to both tags.

then I'll get a count(*) of 4, but when I select columns I get two rows (which is the total count that I want).

View Replies !
Question About Select Count(*) With Group By
suppose a hypothetical table called 'table' with one field called 'field' of
an arbitrary type.

select count(*) from table where field='value' group by field

produces no rows when run under the latest mysql. without "group by" it
produces 1 row.

is this according to the SQL standard or is this just a coincidence? in
other words, can i rely on this behaviour to deduce that there are no fields
with value 'value' in 'table'?

View Replies !
COUNT And GROUP BY In Forum System
I recently built my own forum system in PHP with a MySQL back end. It's been a real learning expererience and I have learned a lot of things. One issue I am having is with developing a top ten posters list to show the last 24 hours only.PHP Code:

 $topday_sql = "SELECT t1.fp_ID, t1.fp_posterID, t1.fp_time, ";
$topday_sql .= "t2.u_ID, t2.u_contact ";
$topday_sql .= "FROM $DBTABLE22 AS t1 ";
$topday_sql .= "LEFT JOIN $DBTABLE11 AS t2 ON t1.fp_posterID=t2.u_ID ";
$topday_sql .= "WHERE fp_time>='".(time()-86400)."' GROUP BY fp_posterID LIMIT 10";
$topday_result = @mysql_query($topday_sql, $DBlink);
while ($topday_myrow = @mysql_fetch_array($topday_result)) {
    print $topday_myrow["u_contact"]." ".$totalposts."<br>";

Table one has has the post IDs, the poster ID, and the time of post. Table two has the Users ID and Users Name. Using the above statement I can get it to list 10 out of all of the users and if I remove LIMIT 10 all the users show up properly. Now I tried numerous things but I can't seem to do is get it to count how many entries there is per person. I was hoping some thing as simple as COUNT(t1.fp_ID) AS totalposts would of worked, but when the info displayes no value seems to return.

View Replies !
How To Get Count Of Rows Returned While Using Group & Having?
i'm using the having keyword to find certain set of rows and they are working properly.

but what i want is , i want to count the total number of rows returned by this query using mysql.

select name,count(date) from emp group by date having count(date)>3;
this returned returns all the names that have more that 3 entries in the same date. it returned 5 rows and how can i get the count of rows(5) the query returned .

View Replies !
Select Group Order And Count All In One?
I have a column that looks a little like this:

Code:
1
1
1
1
2
2
2
3
3
4
Not in order, but those kinds of numbers.

I want to make a query that returns 1, 2, and 3 (in that order) because they have the most occurrences. I would also like it to return the number of occurrences. If it would go faster without the limit, I can stop the results with PHP just let me know

View Replies !
Count And Group By From Separate Table
I'm trying to make a query that will list a count of the number of sales a person has made in a particular area.

My tables are as follows:

sales (id, salesPersonName, location, salesStatus)
sales_status (id, status)

Both sales_status.status and sales.salesStatus are string values containing, eg, No Contact Made, Declined, Further Information, Sale Complete etc

As an example: ........

View Replies !
COUNT And GROUP BY Display All Counted Rows
have a table as follows

ID | ORG | Subject
-----------------------
100 | 14 | Some text
101 | 18 | Text1
102 | 18 | Text3
103 | 14 | Text4
104 | 18 | More text

What query would I need to get the following output? (when I use COUNT(ID) and GROUP BY ORG it only returns 1 ID per ORG)

ORG 14 - 2 results
100
103

ORG 18 - 3 results
101
102
104

View Replies !
How To Create Complex Query With Group By And Count
I have a table usertags:
usertags
------------
- usertagid
- usertagsiteid
- usertagtext

I want to select the usertagtext and count of usertagtext grouped by usertagtext. I only want it to show usertagtext that also have a match in the usertagsiteid to a given value for usertagtext.

Not sure if that makes sense so here is an example: ......

View Replies !
Count Statement
If I want to select a result that based on the value of count (eg.
count(*) > 5), how can I write a sql to do that?

eg.
select count(*)>5
from Flight
where OperationType = "Departure"
group by Airline, Runway
order by Date

View Replies !
Count And Group By Month In 1 Query For A Date Range?
I have a table that has employees work history on it. Basically the only thing I am worried about is the start and end date. My boss wants a report that charts out the quantity of workers for the past 12 months group by the month.

For example

Employee--Start Date--End Date
Charles-----2008-6-3---2009-2-1
Vicky-------2009-1-1---Present

So in this case there would be a quantity of 1 from June 08 to December 08. Then their would be a quantity of 2 from Jan 09 to Feb 09. And Vicky would also be counted for March since she is still working. I can do this by creating PHP functions and putting it all together, but I was just wondering if there was a way to do this all in 1 query.

View Replies !
How Do You Count The Same Field Twice In One Statement
I have an articles table and a comments table, each comment relates to an article. I also have a validated field in comments that's indicated by 1 or 0.

Is it possible to get the total valid and total not valid comments from one sql statement? ......

View Replies !
Can One Get The COUNT And LAST In One MySQL Statement?
To be clearer:
Lets say I have a MySQL table that has 2 columns:
votes tinyint(1)
date_of_last_vote DATE

How can I get the COUNT of all Votes issued to date and the date of the Last vote issued in 1 MySQL statement?

FYI: I am using this statement but it is not working:

SELECT COUNT(vote_id) AS total_votes, LAST(date_voted) AS last_date FROM pv WHERE poll_id = '1600099';

View Replies !
Select Data And Count In One Statement
$q2 = "SELECT *, COUNT(album_id) AS total_albs FROM photo_albums WHERE user_id = $user_id AND deleted = 0 ORDER BY album_id DESC LIMIT 3"; ....

View Replies !
Statement To Count Foreign Keys
I have two tables that I want to use to build a third. They have a many-to-one relationship for one of the columns. Table A has the "one" side of the many-to-one relationship. Table B has many rows that have foreign keys referencing Table A. I want to write a SQL statement that will return rows that tell how many references to each row in Table B are in Table A. For example:

Table A
1 A
2 B
3 C

Table B
1
1
1
2
2
2
2
3
3

I want the statement to return:
A 3
B 4
C 2

View Replies !
Multiple COUNT() In SELECT Statement
SELECT
COUNT(s01_Products.id)
FROM
s01_Products
LEFT JOIN
s01_Attributes
ON
s01_Attributes.product_id = s01_Products.id
LEFT JOIN
s01_Options
ON
s01_Options.attr_id = s01_Attributes.id
WHERE
(
s01_Products.active = 1
) AND (
(
LEFT(s01_Options.prompt,5) = "Small"
) OR (
LEFT(s01_Options.prompt,2) IN (28,30)
)
)


SELECT
COUNT(s01_Products.id)
FROM
s01_Products
LEFT JOIN
s01_Attributes
ON
s01_Attributes.product_id = s01_Products.id
LEFT JOIN
s01_Options
ON
s01_Options.attr_id = s01_Attributes.id
WHERE
(
s01_Products.active = 1
) AND (
(
LEFT(s01_Options.prompt,6) = "Medium"
) OR (
LEFT(s01_Options.prompt,2) IN (32)
)
)
And one for Large and Extra Large...

I would obviously like to combine all 4 queries in to 1 so that I can get my 4 counts in a single,

View Replies !
Doing A Select Statement With An Array To Get A Count
I posted this in the php forum and it was suggested I try it in the MySQL area instead. Sorry if this gets posted more than once.

So here is my problem. I have a series of mysql queries to allow users to set filters for the data that is returned. They are searching for clients (Site_ID) with projects (Request_ID). A single client can have multiple projects. I want to be able to count the number of projects that are returned from a query. Here is the tail end of that code...

View Replies !

Copyright © 2005-08 www.BigResource.com, All rights reserved