I have an array with results = ['5', '2', '11', '12', '4'];
Now I want to make get count SQL SELECTION based on such array, that is make the SELECT IN Array SQL command. I want to return number of of rows that are there in this array from each element, I tried
The SQL Command I tried so far is as in the image provided and my table.
The result you've got is exactly what I would expect from a COUNT statement. I think you forgot to add a GROUP BY company_two.
EDIT
To handle the case of companies not having any entry, you can do:
SELECT s.company_two_id, COUNT(s.id)
FROM supplies_table s
RIGHT OUTER JOIN companies_table c ON s.company_two_id = c.company_id
WHERE company_two_id IN (...)
GROUP BY s.company_two_id;
Try below :
select COALESCE(count(a), 0) from table1 where b in (something) group by b
Related
I'm brand new to SQL and I know this should be easy, but I can't seem to find any reference on how to do specifically what I'm looking for. I've check the archives and I can't find a basic example.
Anyway, all I want is -
SELECT
(COUNT (i.productNumber WHERE i.type = 'type1') AS 'Type 1'),
(COUNT (i.productNumber WHERE i.type = 'type2') AS 'Type 2'),
FROM items AS i
WHERE i.dateadded BETWEEN '2015-03-02' and '2015-03-04'
The two count conditions are different, but both of those queries share that date condition. I've done two distinct select statements and put a UNION between them. That works. The only issue is all of the data appears in one column under the first alias in the statement. I would need each alias to be a new column. I also have to write the date condition in twice.
You could group them by type so you would get a different row for each of them :
SELECT i.type, COUNT(i.productNumber)
FROM items i
WHERE i.dateadded BETWEEN '2015-03-02' AND '2015-03-04'
GROUP BY i.type;
If you really want to have one row, then you could do
SELECT COUNT(b.productNumber) AS 'type1', COUNT(c.productNumber) AS 'type2'
FROM items i
LEFT JOIN items b on b.productNumber = i.productNumber
LEFT JOIN items c on c.productNumber = i.productNumber
WHERE i.dateadded BETWEEN '2015-03-02' AND '2015-03-04'
AND b.type = 'type1'
AND c.type = 'type2';
I have the following query that isn't returning the expected results.
I am trying to get all of the group names from a field, group_id, that potentially has multiple group_ids that are separated by commas (ex., 1,4,5,7,22). My original query returned only the first group listed in the list of groups_ids but did not return any group after the first comma. It returned just under 3,000 records.
To fix this, I tried using the group_concat function. It worked (no error), but it only returned one record when I was expecting close to 3,000.
I am not sure if I am using the function incorrectly or I am just missing code? If there is another function that would work better, I am all for it. Thanks in advance for your help!
My Query:
select `v`.`asset_id` AS `asset_id`,
`v`.`watched_on` AS `watched_on`,
`v`.`status` AS `Completed_Status`,
`va`.`asset_name` AS `asset_name`,
`u`.`fname` AS `fname`,
`u`.`lname` AS `lname`,
group_concat(distinct `g`.`name` separator ',') AS `group_name`
from (((`vm_video_history` `v`
join `vm_users` `u` on((`u`.`id` = `v`.`user_id`)))
left join `vm_groups` `g` on((`g`.`group_id` = `u`.`group_id`)))
left join `vm_assets` `va` on((`va`.`asset_id` = `v`.`asset_id`)))
order by `v`.`user_id`;
I have a bit of a problem. I have a database layout like so:
customer
customer_id, name, age, etc...
customer_survey_question
id, category, caption, type
customer_survey_answer
id, customer_id, customer_survey_question_id, answer
and I need to pull in their answers like so:
name, age, etc..., question 1, question 2, question 3, etc...
Now I could do a sub-query:
SELECT
`customer`.*,
(
SELECT `answer`
FROM `customer_survey_answer`
WHERE `customer_survey_answer`.`customer_id`=`customer`.`customer_id`
AND `id`=1
) AS `question_1`,
(
SELECT `answer`
FROM `customer_survey_answer`
WHERE `customer_survey_answer`.`customer_id`=`customer`.`customer_id`
AND `id`=2
) AS `question_2`,
....
But there is 14 questions and I need to be able to do this pretty quickly and expand up to 80+ questions. What is the best way to approach?
You cannot do this through a query by and of itself.
Look here for some example code: How to merge data from 2 tables with MySQL
What you can do is use an INNER JOIN or GROUP_CONCAT and then reformat the data in your script (whether that be php or another language)
Using JOIN
Unser the circumstances this would likely lead to a large excess/irrelevant data in each row
SELECT c.*, csa.answer
FROM customers c
INNER JOIN
customer_survey_answer csa ON csa.`customer_id`=c.`customer_id`
ORDER BY c.customer_id, csa.customer_survey_question_id
Using GROUP_CONCAT
This will output one cell (csv style) as the answers
SELECT c.*, GROUP_CONCAT(csa.answer) as answers
FROM customers c
INNER JOIN
customer_survey_answer csa ON csa.`customer_id`=c.`customer_id`
GROUP BY c.customer_id
Using a loop
You might also consider querying the database for a list of customers with answers and then running a second query (for each customer returned) to get their answer. This could lead to a large number of queries.
First query:
SELECT * FROM customers
Second query:
SELECT answer
FROM customer_survey_answer
WHERE customer_id = INSERT_CUSTOMER_ID_HERE}
you want to pivot the data
SELECT class,GROUP_CONCAT(member)
FROM tbl
GROUP BY class;
is the basic case
http://www.artfulsoftware.com/infotree/queries.php#78
It is not wise to force DB output into result's columns.
In case you would like to operate over one only customer, make simple question query and then answer query to get everything and put it together outside of DB - in PHP for example.
In case you would like the list of customers with their answers, make first the question query and then make the "answer x customer" query with respective ids and put them together using hashing outside the DB. It works well and fast unless you don't use paging for your output list ;).
Hash can work like this
// suppose we have from database
// $answer_list(id,customer_id,customer_name,question_id,answer)
// $question_list(id,question)
// hash
$customer_list = array();
$customer_hash = array();
foreach ($answer_list as $answer)
{
$customer_id = $answer['customer_id'];
if (!isset($customer_hash[$customer_id]))
{
$customer_list[] = $customer_id;
$customer_hash[$customer_id]['name'] = $answer['customer_name'];
}
$customer_hash[$customer_id]['answer_hash'][$answer['question_id']] = $answer;
}
// output
foreach ($customer_list as $customer_id)
{
echo $customer_hash[$customer_id]['id'];
echo $customer_hash[$customer_id]['name'];
foreach ($question_list as $question)
{
echo $question['question'];
echo $customer_hash[$customer_id]['answer_hash'][$question['id]]['answer'];
}
}
If you want to generate a table in a single query you could use the group by on a query with a single INNER JOIN and then collect the values in several MAX( CASE ... END ) expressions. Sounds complicated at first but it does work reliably (just add another line for each desired column):
SELECT name, age,
MAX(CASE WHEN customer_survey_question_id=1 THEN answer END) a1,
MAX(CASE WHEN customer_survey_question_id=2 THEN answer END) a2,
MAX(CASE WHEN customer_survey_question_id=3 THEN answer END) a3,
MAX(CASE WHEN customer_survey_question_id=4 THEN answer END) a4,
MAX(CASE WHEN customer_survey_question_id=5 THEN answer END) a5,
MAX(CASE WHEN customer_survey_question_id=6 THEN answer END) a6,
MAX(CASE WHEN customer_survey_question_id=7 THEN answer END) a7,
MAX(CASE WHEN customer_survey_question_id=8 THEN answer END) a8,
...
FROM customer c INNER JOIN customer_survey_answer s
ON s.customer_id=c.customer_id
I have following query,
SELECT t_subject.subject, SUM( t_skilllist.skill_level ) AS total_skill, t_users.first_name,
t_skilllist.skill_level
FROM `t_skilllist`
JOIN t_subject ON t_subject.id = t_skilllist.subject_id
JOIN t_users ON t_users.id = t_skilllist.user_id
WHERE t_subject.subject = 'html'
GROUP BY t_users.first_name
ORDER BY total_skill DESC
LIMIT 0 , 30
I want to display subject and skill level for each student. But, for one subject I can do that with above query. As an example for html it works. However, I want to pass more than one subject to the query dynamically. I tried to combined subjects with AND operator but it return empty result set.
How to solve this? How to pass more than two subjects to the query? I am using PHP as server side scripting language.
You can use the IN() clause.
WHERE t_subject.subject IN ('html', 'php', 'and', 'a', 'lot', 'more')
MySQL Server Version: Server version: 4.1.14
MySQL client version: 3.23.49
Tables under discussion: ads_list and ads_cate.
Table Relationship: ads_cate has many ads_list.
Keyed by: ads_cate.id = ads_list.Category.
I am not sure what is going on here, but I am trying to use COUNT() in a simple agreggate query, and I get blank output.
Here is a simple example, this returns expected results:
$queryCats = "SELECT id, cateName FROM ads_cate ORDER BY cateName";
But if I modify it to add the COUNT() and the other query data I get no array return w/ print_r() (no results)?
$queryCats = "SELECT ads_cate.cateName, ads_list.COUNT(ads_cate.id),
FROM ads_cate INNER JOIN ads_list
ON ads_cate.id = ads_list.category
GROUP BY cateName ORDER BY cateName";
Ultimately, I am trying to get a count of ad_list items in each category.
Is there a MySQL version conflict on what I am trying to do here?
NOTE: I spent some time breaking this down, item by item and the COUNT() seems to cause the array() to disappear. And the the JOIN seemed to do the same thing... It does not help I am developing this on a Yahoo server with no access to the php or mysql error settings.
I think your COUNT syntax is wrong. It should be:
COUNT(ads_cate.id)
or
COUNT(ads_list.id)
depending on what you are counting.
Count is an aggregate. means ever return result set at least one
here you be try count ads_list.id not null but that wrong. how say Myke Count(ads_cate.id) or Count(ads_list.id) is better approach
you have inner join ads_cate.id = ads_list.category so Count(ads_cate.id) or COUNT(ads_list.id) is not necessary just count(*)
now if you dont want null add having
only match
SELECT ads_cate.cateName, COUNT(*),
FROM ads_cate INNER JOIN ads_list
ON ads_cate.id = ads_list.category
GROUP BY cateName
having not count(*) is null
ORDER BY cateName
all
SELECT ads_cate.cateName, IFNULL(COUNT(*),0),
FROM ads_cate LEFT JOIN ads_list
ON ads_cate.id = ads_list.category
GROUP BY cateName
ORDER BY cateName
Did you try:
$queryCats = "SELECT ads_cate.cateName, COUNT(ads_cate.id)
FROM ads_cate
JOIN ads_list ON ads_cate.id = ads_list.category
GROUP BY ads_cate.cateName";
I am guessing that you need the category to be in the list, in that case the query here should work. Try it without the ORDER BY first.
You were probably getting errors. Check your server logs.
Also, see what happens when you try this:
SELECT COUNT(*), category
FROM ads_list
GROUP BY category
Your array is empty or disappear because your query has errors:
there should be no comma before the FROM
the "ads_list." prefix before COUNT is incorrect
Please try running that query directly in MySQL and you'll see the errors. Or try echoing the output using mysql_error().
Now, some other points related to your query:
there is no need to do ORDER BY because GROUP BY by default sorts on the grouped column
you are doing a count on the wrong column that will always give you 1
Perhaps you are trying to retrieve the count of ads_list per ads_cate? This might be your query then:
SELECT `ads_cate`.`cateName`, COUNT(`ads_list`.`category`) `cnt_ads_list`
FROM `ads_cate`
INNER JOIN `ads_list` ON `ads_cate`.`id` = `ads_list`.`category`
GROUP BY `cateName`;
Hope it helps?