I am trying to get a count of tickets from my database where there are results with multiple status. If I run:
SELECT status, count(status) AS t_count
FROM `ticket`
WHERE user_id = 123 AND status <=3
GROUP BY status
The result is as follows
status t_count
1 1
2 5
3 17
I am trying to get t_count to show 23 so have written a sub query as follows:
SELECT user_id, sum(status) AS ticket_count
FROM ticket
WHERE (user_id, ticket_count) IN
(SELECT user_id, status, sum(status) AS ticket_count
FROM `ticket` WHERE user_id = 123 GROUP BY status)
GROUP BY user_id
this results in an error of #1054 -
Unknown column 'ticket_count' in 'IN/ALL/ANY subquery'
Can you advise on what I'm doing wrong. Not do subqueries much before and the one I have done are straight forward and examples I've googled don't use counts and sums
Related
In my table of repairs, i want count cars in each status (1,2,3 and 4):
Status 1: 5
Status 2: 0
Status 3: 6
Status 4: 3
As it shows, no cars on status 2, so, i did the same query 4 times with "WHEN status == 'n' to count in each status, and works fine.
Now i want to do in only one query, but in my query:
select status,count(car_id) from repairs GROUP BY status.
show me this:
Status 1: 5
Status 3: 6
Status 4: 3
You're going to need a source, probably a table, which contains every status which you want to appear in the report. One way would be the "calendar table" approach where you join a table containing every status to your current query, e.g.
SELECT
t1.status,
COALESCE(t2.car_cnt, 0) AS car_cnt
FROM
(
SELECT 1 AS status UNION ALL -- replace this ad-hoc subquery with
SELECT 2 UNION ALL -- an actual "calendar" table of statuses
SELECT 3 UNION ALL -- or if you already have such a table, use that
SELECT 4
) t1
LEFT JOIN
(
SELECT status, COUNT(car_id) AS car_cnt
FROM repairs
GROUP BY car_id
) t2
ON t1.status = t2.status
Try this:
SELECT status, count(car_id)
FROM repairs GROUP BY car_id
UNION
SELECT status, 0
FROM repairs WHERE status NOT IN
(SELECT status FROM repairs GROUP BY car_id);
Hello I have the following table design
ID account_id score date
------------------------------------------
1 500 4 x
2 764 4 x
3 500 6 x
4 500 7 x
5 764 5 x
I'm trying to get all rows with the latest account_id entry
so my code should return
ID account_id score date
------------------------------------------
4 500 7 x
5 764 5 x
I tried the following code but it seems to return the first entry but with the latest date
SELECT account_id,score, max(date) from table group by account_id
Case 1: If id is auto-increment column or max(id) means latest row.
select * from
(select * from table_name
order by id desc) temp
group by account_id
Case 2: If date column decides latest row then replace id by date in order clause and group clause.
try it-
SELECT distinct a.id,a.account_id,b.score,b.date
FROM mytable b
JOIN
(
SELECT account_id,MAX(id) AS id
FROM mytable
GROUP BY account_id
) a ON a.account_id=b.account_id
ORDER BY a.id;
This question is just a duplicate of SQL Select only rows with Max Value on a Column
There you'll find a good explanation.
SELECT a.*
FROM table a
INNER JOIN (
SELECT `account_id`,MAX(`date`) AS latest FROM table GROUP BY account_id
) b
ON a.`date` = b.`latest` AND a.`account_id` = b.`account_id`
ORDER BY `date` DESC
Reference :
Using ORDER BY and GROUP BY together
Try using this query it works fine
Select a.account_id,a.score,a.date
from authors as a
join
(Select account_id,max(date) as date
from authors
group by account_id) as d
on(d.date=a.date)
Okay so I have a table that has the following
KEY username password score
The above columns are not in any specific order.
I want to send my Database a username and have it send me back what rank that user name is based on its score. So for example if I had 10 people in there and the 3rd person in has the highest score. When I pass the 3rd persons username in I want it to send back 1.
Is this possible?
I have been trying things like this
$result = mysql_query("SELECT * FROM tablename where username='$username' ORDER BY score DESC");
but it doesnt seem to give me the row number
This will handle ranks that have the same score.
SELECT d.*, c.ranks
FROM
(
SELECT Score, #rank:=#rank+1 Ranks
FROM
(
SELECT DISTINCT Score
FROM tableName a
ORDER BY score DESC
) t, (SELECT #rank:= 0) r
) c
INNER JOIN tableName d
ON c.score = d.score
// WHERE d.username = 'Helen'
SQLFiddle Demo (Ranking with duplicates)
SQLFiddle Demo (with filtering)
for example
KEY username password score Ranks
1 Anna 123 5 3
2 Bobby 345 6 2
3 Helen 678 6 2
4 Jon 567 2 4
5 Arthur ddd 8 1
for better performance, add an INDEX on column Score,
ALTER TABLE tableName ADD INDEX (Score)
SELECT
(SELECT COUNT(*)+1 FROM tablename WHERE score > t.score) as rank,
*
FROM
tablename t
where
username='$username'
The ORDER BY in your query is useless since you're only returning one row.
need a small help to figure out this situation.
I see that codeigniter is not supporting UNION and i want to figure out this method to get the total sum for 2 tables, with same id of product.
The issue is that on sum 2 tables, the values are duplicating or multiplicative.
Link to SQL Fiddle
Structure :
create table products
(id int, name varchar(9));
insert into products
(id, name)
values
(1,'Product 1'),
(2,'Product 2'),
(3,'Product 3');
create table p_items
(puid int, prid int, quantity int);
insert into p_items
(puid, prid, quantity)
values
(11,1,100),
(11,2,100),
(11,2,100),
(14,2,100),
(14,3,100),
(15,3,100);
create table s_items
(puid int, prid int, quantity int);
insert into s_items
(puid, prid, quantity)
values
(11,1,1),
(11,2,1),
(11,2,1),
(13,2,1),
(15,3,1),
(13,3,1);
Execute in normal SQL:
select a.puid, b.name, a.prid, sum(a.quantity) as P_ITEMS, sum(c.quantity) as S_ITEMS
from p_items a
join products b
on b.id = a.prid
join s_items c
on c.prid = a.prid
group by a.prid;
Codeigniter Function:
$this->alerts
->select('products.id as productid, products.name, sumt(p_items.quantity), sum(s_items.quantity)', FALSE)
->from('products')
->join('p_items', 'products.id = p_items.prid', 'left')
->join('s_items', 'products.id = s_items.prid')
->group_by("products.id");
echo $this->alerts->generate();
Any help is very appreciated.
Your problem is your producing a cartesian product and thus getting your duplicated sums. Look at Product ID 3 for example. You're associating that with p_items prid = 3. By itself, that would return you 200. However, once you then join on s_items prid = 3, now for each row in s_items, it has to match with each row in p_items. Meaning:
14 3 100 15 3 1
14 3 100 15 3 1
15 3 100 15 3 1
15 3 100 15 3 1
---------------
400 4
Besides the product table, which table is your master table? If you use p_items, you want get row 13 from s_items. Likewise, if you use s_items, you won't get rows 14 from p_items.
You can accomplish this using a subquery:
select b.id,
b.name,
P_ITEMS,
S_ITEMS
from products b
left join
(SELECT prid, SUM(quantity) as P_Items
FROM p_items
GROUP BY prid)
a on b.id = a.prid
left join
(SELECT prid, SUM(quantity) as S_Items
FROM s_items
GROUP BY prid)
c on c.prid = a.prid
group by b.id, b.name
And the updated Fiddel: http://sqlfiddle.com/#!2/62b45/12
Good luck.
If the best way to get the answer you want is with a union query, and codeigniter does not let you write one, don't use codeigniter to write your query. Put it in a stored procedure and call the stored procedure with codeigniter.
Here I am with a problem I can't solve myself.
My problem is:
I need to SELECT the count of a column, but I also need to GROUP BY on that same column. What I've tried so far is not returning as I expected.
Here is what I tried:
'SELECT COUNT(user_id) AS total_donors
FROM ' . DONATION_SECURITY_TABLE .
" WHERE payment_status = 'Completed'
GROUP BY user_id"
This is how my table looks like:
id user_id payment_status
1 20 Completed
2 33 Completed
3 44 Completed
4 20 Pending
5 33 Pending
6 44 Completed
7 20 Completed
As you see, a single user_id can be Pending or Completed more than once, but I want my query to return 3 (based on the table example above).
So, I want my query to COUNT GROUPED user_ids if payment status is completed.
Ideas?
You can use the DISTINCT keyword to select the unique User ID's like so
"SELECT COUNT(DISTINCT user_id) AS total_donors
FROM " . DONATION_SECURITY_TABLE .
" WHERE payment_status = 'Completed'
sounds like a distinct count is what you need. throw away the group by and try this:
SELECT
COUNT(DISTINCT user_id) AS total_donors
FROM
mytable
WHERE
payment_status = 'Completed'
For a result of 3, replace your Count(user_id) with Count(distinct user_id) and remove the group by.
That gives you the count of unique user_ids with a payment status of completed.
Use this:
SELECT COUNT(DISTINCT `user_id`) as `Total` FROM `Donation_Table`
WHERE `payment_status` = 'Completed'
since you are only interested on the count of user_ID, you don't need to use GROUP BY clause
SELECT COUNT(DISTINCT user_ID)
FROM tableName
WHERE payment_status = 'completed'
when you try to add GROUP BY clause. the result is very different from what you are expecting.