MySQL query printing double records - php

All recorders in sales & purchase table are only entered Once. I have checked it carefully. However I wish to combine these two tables in such a way that both tables will be completely fetched. here is my query
note that timestamp column has mysql DATE format
Select
sales.ID as sid,
sales.saleHatsh,
sales.timestamp as sdate,
sales.gatePass as sGP,
sales.pname as sPN,
sales.description as sDES,
sales.balance as sbal,
purchase.ID as pid,
purchase.purchaseHatsh,
purchase.timestamp as pdate,
purchase.gatePass as pGP,
purchase.pname as pPN,
purchase.description as pDES,
purchase.balance as pbal
from sales,purchase
where sales.timestamp='2013-11-11' OR purchase.timestamp='2013-11-11'
here is the result of my query & sales & purchase table
Sales table only have 2 recorder
Purchase table only has 4 recorder

What is happening there is that you are not joining those tables in any way. so you are getting all the possible matches from those tables. Looking at the columns i don't think you want to JOIN, but probably you want a UNION instead:
SELECT
sales.ID AS id,
sales.saleHatsh AS hatsch,
sales.TIMESTAMP AS date,
sales.gatePass AS GatePass,
sales.pname AS pname,
sales.description AS Description,
sales.balance AS balance,
'SALE' AS transanctionType
FROM sales
WHERE sales.TIMESTAMP = '2013-11-11'
UNION
SELECT
purchase.ID,
purchase.purchaseHatsh,
purchase.TIMESTAMP,
purchase.gatePass,
purchase.pname,
purchase.description,
purchase.balance,
'PURCHASE'
FROM purchase
WHERE purchase.TIMESTAMP = '2013-11-11'
I added a column "transactionType" for you to identify which ones are sales or purchases.

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.

how to get dates between two given dates in sql

in the above table i need sql query by which i can return dates between Leave_from and Leave_to from leave_log Table (eg, Leave_from 30/07/2018 Leave_to 02-08-2018) i need dates like
30/07/2018
01/08/2018
02/08/2018
by which i will try next query
2) is der any query or function which will check before insert into leave_log table whether the leaves applied by the employees for particular date (01-08-2018) does not cross quota of 10% per Team
Thanks in advance
First, you should have a calender table if yes, then you need to JOIN with your actual table to calender table. In other way you can use recursive CTE option :
with t as (
select id, leave_frm, leave_to
from table
union all
select id, dateadd(day, 1, leave_frm), leave_to
from t
where leave_frm < leave_to
)
select *
from t
option (maxrecursion 0);

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

mysql sum columns from multiple tables

I have two tables: tb_subjoe and tb_deliverydetails
I need to sum Price and Quantity column. at this my code mysql When I do
SELECT scode_id, scode_detail, deli_quote, SUM(deli_dequan) AS QUANTITY, SUM(deli_goodsprice) AS Good price, SUM(deli_wagesprice) AS Wage price
FROM tb_deliverydetails
LEFT JOIN tb_subjob
ON tb_subjob.scode_id = tb_deliverydetails.scode_id
GROUP BY `deli_quote`
it not answer for me

COUNT values in column and produce table of results mysql

To preface this question - I know I'm missing something really obvious here but it is Friday afternoon!
I'm trying to COUNT to number of times certain values appear within the same column and produce a table of the results.
Here's my code so far:
MYSQL
SELECT COUNT(order_status) as printed
FROM orders WHERE order_status = 'Printed Order'
UNION
SELECT COUNT(order_status) as charged
FROM orders WHERE order_status = 'Charged Order'
UNION
SELECT COUNT(order_status) as exchanged
FROM orders WHERE order_status = 'Exchanged Order'
UNION
SELECT COUNT(order_status) as refunded
FROM orders WHERE order_status = 'Refunded Order'
UNION
SELECT COUNT(order_status) as cancelled
FROM orders WHERE order_status = 'Cancelled Order'
GROUP BY order_status
Result of the above query
printed
-------
224
19190
593
2618
2899
The code is producing the correct figures, however, I would prefer the result to look as follows:
Desired result
printed - 224
charged - 19190
exchanged - 593
refunded - 2618
cancelled -2899
This way I can easily reference them via associative array call i.e. $order_status['printed']
Any help would be great.
Add a column specifying the type. The easiest way is to use group by:
select order_status, count(*)
from orders o
group by order_status;
If you use PDO, set the fetch mode to create associative arrays by default by:
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
try:
SELECT order_status, COUNT(order_status) as printed
FROM orders WHERE order_status = 'Printed Order'
GROUP BY order_status

Categories