Add count from two queries in codeigniter? - php

I have 4 tables
I query:-
1. activity: having activity id
2. activity_specialties:having activity id and specialties
3. users: specialties
4. List item
II query:
activity: having activity id
icd10_assignments:activity_assignment_id
I have to find count from I query and II query
and add those count result to find total result
my columns are activity id and total count
My two queries are
1)
SELECT `activity`.`activity_id`, count(distinct users.id) as user_id
FROM (`activity`)
JOIN `activity_specialties` ON `activity`.`activity_id` = `activity_specialties`.`activity_id`
LEFT JOIN `users` ON `users`.`specialty`= `activity_specialties`.`specialties_id`
WHERE `activity_category` = 'Online CME Activities'
GROUP BY `activity`.`activity_id`
2)
SELECT `activity`.`activity_id`, count(icd10_assignments.id) as assign_id
FROM (`activity`)
JOIN `icd10_assignments`
ON `activity`.`activity_id`= `icd10_assignments`.`activity_assignment_id`
WHERE `activity_category` = 'Online CME Activities'
GROUP BY `activity`.`activity_id`

Related

How to create new table for the output of DISTINCT COUNT to be distributed in rows, not in column?

My query displays the DISTINCT count of buyers with corresponding ticketserial#. I need to automatically calculate the SOLD and BALANCE column and save into the database either into the existing table (table1) with the rows that corresponds to the ticketserial. I've already exhausted my brain and did google many times but I just can't figure it out. So I tried another option by trying to create a new table into the database for the output of DISTINCT COUNT but I didn't find any sample query to follow, so that I could just use INNER JOIN for that new table with table1, with that the PRINTED, SOLD are in the same table, thus I can subtract these columns to obtain the values for the BALANCE column.
Existing table1 & table2 are records in the database via html form:
Table1
Ticket Serial Printed Copies SOLD(sold) Balance
TS#1234 50 ?(should be auto ?
TS#5678 80 ?(should be auto ?
(so on and so forth...)
Table2
Buyer Ticket Serial
Adam TS#1234
Kathy TS#1234
Sam TS#5678
(so on and so forth...)
The COUNT DISTINCT outputs the qty. of sold tickets:
<td> <?php print '<div align="center">'.$row['COUNT(ticketserial)'];?></td>
...
$query = "SELECT *, COUNT(ticketserial) FROM buyers WHERE ticketsold != 'blank' GROUP BY
ticketserial ";
It's COUNT output looks like this:
Ticket Serial------Distinct Count
TS#1234 7
TS#5678 25
(so on and so forth...)
I tried to update the SOLD column and BALANCE column by UPDATE or INSERT and foreach loop but only the first row in table was updated.
Table1
Ticket Serial Printed Copies Sold Balance
TS#1234 50 **7** 0
TS#5678 80 **0** 0
TS#8911 40 **0** 0
(so on and so forth...)
Note: The fieldname "sold" in table1 is not the same with the fieldname "ticketsold" in table2 as the former is quantity and the later is ticketserials.
Your question is a bit hard to follow. However this looks like a left join on a aggregate query:
select
t1.ticket_serial,
t1.printed_copies,
coalesce(t2.sold, 0) sold,
t1.printed_copies - coalesce(t2.sold, 0) balance
from table1 t1
left join (
select ticket_serial, count(*) sold
from table2
group by ticket_serial
) t2 on t2.ticket_serial = t1.ticket_serial
If you are looking to update the main table:
update table1 t1
left join (
select ticket_serial, count(*) sold
from table2
group by ticket_serial
) t2 on t2.ticket_serial = t1.ticket_serial
set
t1.sold = coalesce(t2.sold, 0),
t1.balance = t1.printed_copies - coalesce(t2.sold, 0)
I would not actually recommend storing the sold and balance in the main table - this is derived information that can be easily computed when needed, and would be tedious to maintain. If needed, you could create a view using the first above SQL statement, which will give you an always up-to-date perspective at your data.

Select rows from 2 tables in 1 query

Need to select name,domain from table 1, than I need a sum of values from a column from table 2 with condition table1.id = table2.
Table 2 does not have the same number of columns.
I have tried joining 2 queries with UNION and UNION ALL, but i keep getting the same problem of different number of columns.
$rows = $test->query('select domain,name from customers
UNION
select SUM(customer_id) from main.rentals,main.customers where customer_id = customers.id');
Expected would be "User's Name" - "domain" - "number of rentals(integer)"
Warning: SQLite3::query(): Unable to prepare statement: 1, SELECTs to the left and right of UNION do not have the same number of result columns
If you use SUM, it will sum all ids, for example if you have a customer ID of 10 and it shows 5 times the result will be 50. In the other hand if you use count it will count the rows that that id was shown. That's why we are doing a group by. You may tweak it to fill your specific needs, but this is one way to achieve what you want.
$query = "
SELECT
domain,
name,
count(customer_id) as Total
FROM
customers
left join main.rentals on customers.id = customer_id
GROUP BY
customer_id
";
$test->query($query );

Sum columns on different tables and multiply by value of a column on another table

I need to compute employees' monthly salaries based on meetings attended, deductions and bonuses given;
Employees have different pay per meeting based on their job position.
The solution is:
salary = (Pay_per_minute * meetings_attended) + bonuses - deductions ;
I have four tables:
Jobs: Id, title, pay_per_meeting
Employees: Id, Name, job_id
Bonuses: Id, amount, employee_id, date
Deductions: Id, amount, employee_id, date
Meetings: Id, employee_id, date
SELECT
COUNT(meetings.employee_id) as meetings_attended,
COUNT(deductions.amount) as debt,
COUNT(bonuses.amount) bonus,
(SELECT jobs.pay_per_attendance from jobs where jobs.id = (select job_id from employees where id=meetings.employee_id)) as pay,
((meetings_attended * pay) + bonus - debt) as salary
FROM meetings
JOIN deductions ON deductions.employee_id = meetings.employee_id
JOIN bonuses ON bonuses.employee_id = meetings.employee_id
WHERE meetings.employee_id = 1
GROUP BY MONTH(meetings.date), MONTH(deductions.date), MONTH(bonuses.date)
The above query returns many incorrect values whenever i remove the salary line but gives error of unknown column pay, meetings_attended, debt and bonus, am sure something is wrong with the grouping but i can't just see it.
You can't refer to column aliases in the same select list as they're defined, you need to refer to the underlying column. And a subquery can't access an aggregate calculated in the main query. You need to repeat the aggregate expression, or move everything into a subquery and do the calculation with it in an outer query.
Also, all your COUNT() expressions are going to return the same thing, since they're just counting rows (I assume none of the values can be NULL). You probably want COUNT(DISTINCT <column>) to get different counts, and you need to use a column that's unique, so they should be the primary key column, e.g. COUNT(DISTINCT deductions.id).
Another problem is that when you try to sum and count values when you have multiple joins, you end up with a result that's too high, because rows get duplicated in the cross product of all the tables. See Join tables with SUM issue in MYSQL. The solution is to calculate the sums from each table in subqueries.
SELECT m.month, m.meetings_attended, d.debt, b.bonus,
m.meetings_attended * j.pay_per_meeting + b.amount - d.amount AS salary
FROM (
SELECT MONTH(date) AS month, COUNT(*) AS meetings_attended
FROM meetings
WHERE employee_id = 1
GROUP BY month) AS m
JOIN (
SELECT MONTH(date) AS month, COUNT(*) AS bonus, SUM(amount) AS amount
FROM bonuses
WHERE employee_id = 1
GROUP BY month) AS b ON m.month = b.month
JOIN (
SELECT MONTH(date) AS month, COUNT(*) AS debt, SUM(amount) AS amount
FROM deductions
WHERE employee_id = 1
GROUP BY month) AS d ON m.month = d.month
CROSS JOIN employees AS e
JOIN jobs AS j ON j.id = e.job_id
WHERE e.employee_id = 1

how to get count of another table

Like below image I have two tables, now I want to get all columns from Restaurant table depending on cat column, and number of records from Foods table that have that Restaurant id.
example : (to get 1,test from Restaurant table and 3 from Foods table).
$sql = "select * from Restaurant,Foods where cat=6..." ;
updated :
$sql = "r.*,(SELECT COUNT(*) FROM restaurant_foods WHERE restaurant_id = r.id)
foods_count FROM restaurant r WHERE r.cats LIKE '%,$cat,%' limit $start,$end"
That should do the job:
SELECT r.*,
(SELECT Count(*)
FROM Foods
WHERE restaurnat_id = r.id) foods_count
FROM Restaurant r
WHERE r.cat = 6

desperate with complicated join query (mysql & php)

okay, i'm setting up a multi-user chat system.
i have a messages table, that holds all the messages - simplified:
messages:
id,
content,
thread_id
then i have a threads table:
messages_threads:
id,
participantlist_id
then i have a participantlist table:
participantlist:
list_id,
name
and i have a participantlist_links table:
participantlist_links:
list_id,
participant_id
now i'd like to find out the thread id from a list (array) of participants, i came up with this:
$threadid_sqlquery = "
SELECT messages_threads.id FROM messages_threads
JOIN participantlist_links
ON messages_threads.participantlist_id = participantlist_links.list_id";
foreach($participants_array as &$participant_id){
$maxid_sqlquery .= "
AND participantlist_links.participant_id='".$participant_id."'";
}
but now: i'm looking for the thread_id of a chat between users 1 and 2 - there is a multi-user chat with users 1,2,3 and a chat with users 1,2,3,4 i get a result of three rows, but i only want the one where only users 1 and 2 are participants.
is there any way to query for that?
SELECT mt.id
FROM (
SELECT list_id
FROM participantlist_links pll
WHERE participant_id IN (1, 2)
GROUP BY
list_id
HAVING COUNT(*) = 2
) q
JOIN message_threads mt
ON mt.participantlist_id = q.list_id
WHERE NOT EXISTS
(
SELECT NULL
FROM participantlist_links pll
WHERE pll.list_id = q.list_id
AND pll.participant_id NOT IN (1, 2)
)
Create the following indexes:
participantlist_links (participant_id, list_id) -- unique
participantlist_links (list_id)

Categories