I have tow tables tbl_product_checkout and tbl_product_checkout_status in which I want to get the last row from tbl_product_checkout_status
//tbl_product_checkout
product_checkout_id user_id product_checkout_order_no
-----------------------------------------------------------
1 1 ORD123456
//tbl_product_checkout_status
checkout_status_id product_checkout_id checkout_status_check
------------------------------------------------------------------
1 1 Dispatched
2 1 Delivered
I have tried using the following query
SELECT *
FROM tbl_product_checkout pc
LEFT
JOIN tbl_product_checkout_status cs
ON cs.product_checkout_id = pc.product_checkout_id
WHERE pc.user_id = 1
GROUP
BY pc.product_checkout_id
ORDER
BY cs.checkout_status_id DESC
but the output for above query is,
user_id product_checkout_order_no checkout_status_check
-------------------------------------------------------------
1 ORD123456 Dispatched
but I want the result as,
user_id product_checkout_order_no checkout_status_check
-------------------------------------------------------------
1 ORD123456 Delivered
Add a where = max sub query eg
DROP TABLE IF EXISTS tbl_product_checkout,tbl_product_checkout_status;
CREATE TABLE tbl_product_checkout(product_checkout_id INT, user_id INT, product_checkout_order_no VARCHAR(20));
INSERT INTO tbl_product_checkout VALUES
( 1 , 1 , 'ORD123456');
CREATE TABLE tbl_product_checkout_status(checkout_status_id INT, product_checkout_id INT, checkout_status_check VARCHAR(20));
INSERT INTO tbl_product_checkout_status VALUES
( 1 , 1 , 'Dispatched'),
( 2 , 1 , 'Delivered');
SELECT * FROM
tbl_product_checkout T1
LEFT JOIN tbl_product_checkout_status T2 ON T1.PRODUCT_CHECKOUT_ID = T2.PRODUCT_CHECKOUT_ID
WHERE T2.CHECKOUT_STATUS_ID = (
SELECT MAX(T3.CHECKOUT_STATUS_ID)
FROM tbl_product_checkout_status T3
WHERE T3.PRODUCT_CHECKOUT_ID = T2.PRODUCT_CHECKOUT_ID
)
;
Result
+---------------------+---------+---------------------------+--------------------+---------------------+-----------------------+
| product_checkout_id | user_id | product_checkout_order_no | checkout_status_id | product_checkout_id | checkout_status_check |
+---------------------+---------+---------------------------+--------------------+---------------------+-----------------------+
| 1 | 1 | ORD123456 | 2 | 1 | Delivered |
+---------------------+---------+---------------------------+--------------------+---------------------+-----------------------+
1 row in set (0.00 sec)
I think your group by mess up your desired outcome. I worked on your given database schema and cretaed a fiddle and managed to get your desired outcome. So your sql should be something like this:
SELECT * FROM tbl_product_checkout as pc
LEFT JOIN tbl_product_checkout_status as cs ON
cs.product_checkout_id = pc.product_checkout_id
WHERE pc.user_id = 1 ORDER BY cs.checkout_status_id DESC limit 1
By using limit 1, you will get last row as we ordered by DESC.
Keep in mind that i removed date part since there was no date on your example code.
Check Out Fiddle
Related
I want to fetch data from two table and apply arithmetic operation on the column.
This is wha I tried :
String sql = "SELECT SUM(S.san_recover-C.amount) as total
FROM sanction S
LEFT JOIN collection C ON S.client_id = C.client_id
WHERE S.client_id=?";
This code is working only when there is value in both tables, but if there is no value in one of two tables there is no result.
SELECT SUM(S.san_recover - C.amount) as total
FROM sanction S
LEFT JOIN collection C ON S.client_id = C.client_id
WHERE S.client_id = ?
The problem with your query lies in the SUM() function. When the left join does not bring back records, then c.amount is NULL. When substracting NULL from something, you get a NULL result, which then propagates across the computation, and you end up with a NULL result for the SUM().
You probably want COALESCE(), like so:
SELECT SUM(S.san_recover - COALESCE(C.amount, 0)) as total
FROM sanction S
LEFT JOIN collection C ON S.client_id = C.client_id
WHERE S.client_id = ?
Where there is a possibility that a client may exist in one table but no another a full join would be appropriate but since mysql does not have such a thing then a union in a sub query will do
drop table if exists sanctions,collections;
create table sanctions(client_id int, amount int);
create table collections(client_id int, amount int);
insert into sanctions values
(1,10),(1,10),(2,10);
insert into collections values
(1,5),(3,10);
Select sum(Samount - camount)
From
(Select sum(amount) Samount, 0 as camount from sanctions where client_id =3
Union all
Select 0,sum(amount) as camount from collections where client_id =3
) s
;
+------------------------+
| sum(Samount - camount) |
+------------------------+
| -10 |
+------------------------+
1 row in set (0.00 sec)
If you want to do this for all clients
Select client_id,sum(Samount - camount) net
From
(Select client_id,sum(amount) Samount, 0 as camount from sanctions group by client_id
Union all
Select client_id,0,sum(amount) as camount from collections group by client_id
) s
group by client_id
;
+-----------+------+
| client_id | net |
+-----------+------+
| 1 | 15 |
| 2 | 10 |
| 3 | -10 |
+-----------+------+
3 rows in set (0.00 sec)
I have table users AND orders. After every UPDATE row in orders. I want update DATA in users table namely concat(OLD.DATA + ID which was updated).
Table 'users'.
ID NAME DATA
1 John 1|2
2 Michael 3|4
3 Someone 5
Table 'orders'.
ID USER CONTENT
1 1 ---
2 1 ---
3 2 ---
4 2 ---
5 3 ---
For example:
SELECT `data` from `users` where `id` = 2; // Result: 3|4
UPDATE `orders` SET '...' WHERE `id` > 0;
**NEXT LOOP**
UPDATE `users` SET `data` = concat(OLD.data, ID.rowUpdated) WHERE `user` = 1;
UPDATE `users` SET `data` = concat(OLD.data, ID.rowUpdated) WHERE `user` = 1;
UPDATE `users` SET `data` = concat(OLD.data, ID.rowUpdated) WHERE `user` = 2;
UPDATE `users` SET `data` = concat(OLD.data, ID.rowUpdated) WHERE `user` = 2;
UPDATE `users` SET `data` = concat(OLD.data, ID.rowUpdated) WHERE `user` = 3;
Result:
SELECT data from users where id = 1; // Result: 1|2|1|2
SELECT data from users where id = 2; // Result: 3|4|3|4
SELECT data from users where id = 3; // Result: 5|5
How can I do it?
I think you are making the same mistake I made not too long ago, ie storing an array/object in a column.
I would recommend using the following tables in your scenario:
users
+-----------+-----------+
| id | user_name |
+-----------+-----------+
| 1 | John |
+-----------+-----------+
| 2 | Michael |
+-----------+-----------+
orders
+-----------+-----------+------------+
| id | user_id |date_ordered|
+-----------+-----------+------------+
| 1 | 1 | 2019-03-05 |
+-----------+-----------+------------+
| 2 | 2 | 2019-03-05 |
+-----------+-----------+------------+
Where user_id is the foreign key to users
sales
+-----------+-----------+------------+------------+------------+
| id | order_id | item_sku | qty | price |
+-----------+-----------+------------+------------+------------+
| 1 | 1 | 1001 | 1 | 2.50 |
+-----------+-----------+------------+------------+------------+
| 2 | 1 | 1002 | 2 | 3.00 |
+-----------+-----------+------------+------------+------------+
| 3 | 2 | 1001 | 2 | 2.00 |
+-----------+-----------+------------+------------+------------+
where order_id is the foreign key to orders
Now for the confusing part. You will need to use a series of JOINs to access the relevant data for each user.
SELECT
t3.id AS user_id,
t3.user_name,
t1.id AS order_id,
t1.date_ordered,
SUM((t2.price * t2.qty)) AS order_total
FROM orders t1
JOIN sales t2 ON (t2.order_id = t1.id)
LEFT JOIN users t3 ON (t1.user_id = t3.id)
WHERE user_id=1
GROUP BY order_id;
This will return:
+-----------+--------------+------------+------------+--------------+
| user_id | user_name | order_id |date_ordered| order_total |
+-----------+--------------+------------+------------+--------------+
| 1 | John | 1 | 2019-03-05 | 8.50 |
+-----------+--------------+------------+------------+--------------+
These type of JOIN statements should come up in basically any project using a relational database (that is, if you are designing your DB correctly). Typically I create a view for each of these complicated queries, which can then be accessed with a simple SELECT * FROM orders_view
For example:
CREATE
ALGORITHM = UNDEFINED
DEFINER = `root`#`localhost`
SQL SECURITY DEFINER
VIEW orders_view AS (
SELECT
t3.id AS user_id,
t3.user_name,
t1.id AS order_id,
t1.date_ordered,
SUM((t2.price * t2.qty)) AS order_total
FROM orders t1
JOIN sales t2 ON (t2.order_id = t1.id)
LEFT JOIN users t3 ON (t1.user_id = t3.id)
GROUP BY order_id
)
This can then be accessed by:
SELECT * FROM orders_view WHERE user_id=1;
Which would return the same results as the query above.
Depending on your needs, you will probably need to add a few more tables (addresses, products etc.) and several more rows to each of these tables. Very often you will find that you need to JOIN 5+ tables into a view, and sometimes you might need to JOIN the same table twice.
I hope this helps despite it not exactly answering your question!
It is probably a bad idea to update the USERS table after inserting into (or updating) the ORDERS table. Avoid storing data twice. In your case: you can always get all "order ids" for a user by querying the ORDERS table. Thus, you don't need to store them in the USERS table (again). Example (tested with MySQL 8.0, see dbfiddle):
Tables and data
create table users( id integer primary key, name varchar(30) ) ;
insert into users( id, name ) values
(1, 'John'),(2, 'Michael'),(3, 'Someone') ;
create table orders(
id integer primary key
, userid integer
, content varchar(3) references users (id)
);
insert into orders ( id, userid, content ) values
(101, 1, '---'),(102, 1, '---')
,(103, 2, '---'),(104, 2, '---'),(105, 3, '---') ;
Maybe a VIEW - similar to the one below - will do the trick. (Advantage: you don't need additional columns or tables.)
-- View
-- Inner SELECT: group order ids per user (table ORDERS).
-- Outer SELECT: fetch the user name (table USERS)
create or replace view userorders (
userid, username, userdata
)
as
select
U.id, U.name, O.orders_
from (
select
userid
, group_concat( id order by id separator '|' ) as orders_
from orders
group by userid
) O join users U on O.userid = U.id ;
Once the view is in place, you can just SELECT from it, and you will always get the current "userdata" eg
select * from userorders ;
-- result
userid username userdata
1 John 101|102
2 Michael 103|104
3 Someone 105
-- add some more orders
insert into orders ( id, userid, content ) values
(1000, 1, '***'),(4000, 1, '***'),(7000, 1, '***')
,(2000, 2, ':::'),(5000, 2, ':::'),(8000, 2, ':::')
,(3000, 3, '###'),(6000, 3, '###'),(9000, 3, '###') ;
select * from userorders ;
-- result
userid username userdata
1 John 101|102|1000|4000|7000
2 Michael 103|104|2000|5000|8000
3 Someone 105|3000|6000|9000
I am a student and beginner in SQL
I have a table that has columns: ID_USER, DATE and PAYMENT_DUMMY, which contains information about user payments in each month (1 - paid, 0 - did not pay).
I need to create another dummy variable that will identify users who did not pay in the first or first and second months, but paid in the remaining (in the screenshot, these are users are 1225964 and 1249528).
Can anyone help me on this?
Perhaps this where the inner query allocates a row number and the outer query works out how many of the first 2 month have not been paid
drop table if exists t;
create table t(id int, dt date, dummy int);
insert into t values
(1,'2018-01-31',1),(1,'2018-02-28',1),(1,'2018-03-31',1),
(2,'2018-01-31',0),(2,'2018-02-28',0),(2,'2018-03-31',1),
(3,'2018-01-31',1),(3,'2018-02-28',0),(3,'2018-03-31',1),
(4,'2018-01-31',0),(4,'2018-02-28',0),(4,'2018-03-31',0);
select s.id,sum(dummy) cnt
from
(
select t.*,
if (t.id <> #p,#r:=1,#r:=#r+1) r,
#p:=t.id p
from t
cross join (select #r:=0,#p:=0) rn
order by t.id,t.dt
) s
where s.r <= 2
group by s.id having cnt = 0;
+------+------+
| id | cnt |
+------+------+
| 2 | 0 |
| 4 | 0 |
+------+------+
2 rows in set (0.00 sec)
I've seen many questions along this issue, but can't get this to work.
I want to UPDATE multiple columns in a table (but will start with one) based upon a calculated value from the same table.
It is a list of transactions per customer, per month.
TransID | Cust | Month | Value | PastValue | FutureValue
1 | 1 | 2018-01-01 | 45 |
2 | 1 | 2018-02-01 | 0 |
3 | 1 | 2018-03-01 | 35 |
4 | 1 | 2018-04-01 | 80 |
.
UPDATE tbl_transaction a
SET PrevMnthValue =
(SELECT COUNT(TransactionID) FROM tbl_transaction b WHERE b.Cust=a.Cust AND b.Month<a.Month)
But we get the dreaded 'Can't update a table using a where with a subquery of the same table).
I've tried to nest the subquery as this has been touted as a workaround:
UPDATE tbl_transactions a
SET
PastValue =
(
SELECT CNT FROM
(
SELECT
COUNT(TransactionID) AS CNT
FROM tbl_transactions b
WHERE
b.CustomerRef=a.CustomerRef AND b.Month<a.Month
) x
),
FutureValue =
(
SELECT CNT FROM
(
SELECT
COUNT(TransactionID) AS CNT
FROM tbl_transactions b
WHERE
b.CustomerRef=a.CustomerRef AND b.Month>a.Month
) x
)
But I get an UNKNOWN a.CustomerRef in WHERE clause. Where am I going wrong?
You can't update and read from one table at the same time.
MySQL documentation tell about it
You cannot update a table and select from the same table in a subquery.
At first you must select necessary data and save them to somewhere, for example to temporary table
CREATE TEMPORARY TABLE IF NOT EXISTS `temp` AS (
SELECT
COUNT(`TransactionID`) AS CNT,
`CustomerRef`,
`Month`
FROM `tbl_transactions`
GROUP BY `Custom,erRef`, `Month`
);
After it, you can use JOIN statement for update table
UPDATE `tbl_transactions` RIGTH
JOIN `temp` ON `temp`.`CustomerRef` = `tbl_transactions`.`CustomerRef`
AND `temp`.`Month` < `tbl_transactions`.`Month`
SET `tbl_transactions`.`PastValue` = `temp`.`cnt`
UPDATED: if you want to update several columns by different condition you can combine temporary table, UPDATE + RIGHT JOIN and CASE statement. For example:
UPDATE `tbl_transactions`
RIGTH JOIN `temp` ON `temp`.`CustomerRef` = `tbl_transactions`.`CustomerRef`
SET `tbl_transactions`.`PastValue` = CASE
WHEN `temp`.`Month` < `tbl_transactions`.`Month` THEN `temp`.`cnt`
ELSE `tbl_transactions`.`PastValue`
END,
`tbl_transactions`.`FutureValue` = CASE
WHEN `temp`.`Month` > `tbl_transactions`.`Month` THEN `temp`.`cnt`
ELSE `tbl_transactions`.`FutureValue`
END
You can try below
UPDATE tbl_transactions a
Join
( SELECT CustomerRef,COUNT(TransactionID) AS CNT FROM tbl_transactions b
group by CustomerRef)x
SET PastValue = CNT
WHERE x.CustomerRef=a.CustomerRef AND x.Month<a.Month
So, I have two data and they did't have any relationship
first Table
tglAmbil Satuan Harga
11-08-2017 1 10000
11-08-2017 2 10000
15-08-2017 2 10000
01-09-2017 2 10000
Second Table
tglAmbil Satuan Harga
21-08-2017 1 10000
And I try to make my SELECT result look like this:
Month(tglAmbil) date_format(tglAmbil,"$m") Harga
8 Agustus 60000
9 September 20000
using this query:
SELECT
MONTH(`tglAmbil`),
DATE_FORMAT(tglAmbil,"%M"),
SUM(detaillpjunbudged.satuan * detaillpjunbudged.harga) +
IFNULL(prokers.total,0)
FROM `unbudged` LEFT JOIN lpjunbudged ON unbudged.kdUnbudgeding =
lpjunbudged.kdUnbudgeding
LEFT JOIN detaillpjunbudged ON lpjunbudged.kdLpjUnbudged =
detaillpjunbudged.kdLpjUnbudged,
(SELECT MONTH(`tglAmbil`) AS
tgl,DATE_FORMAT(tglAmbil,"%M"),SUM(detaillpjproker.satuan *
detaillpjproker.harga) AS total,`kdDetailProker` FROM `realisasiproker` LEFT
JOIN lpjproker ON realisasiproker.kdRealisasiProker =
lpjproker.kdRealisasiProker LEFT JOIN detaillpjproker ON lpjproker.kdLPJ =
detaillpjproker.kdLPJ GROUP BY MONTH(tglAmbil)) AS prokers
WHERE MONTH(`tglAmbil`) = prokers.tgl GROUP BY MONTH(`tglAmbil`)
but the result that I got is:
Month(tglAmbil) date_format(tglAmbil,"$m") Harga
8 Agustus 60000
so, what the real cause? I confused with this sytax problem. Thank you
Consider the following:
DROP TABLE IF EXISTS table1;
CREATE TABLE table1
(purchase_date DATE NOT NULL
,quantity INT NOT NULL
,price INT NOT NULL
);
INSERT INTO table1 VALUES
('2017-08-11',1,10000),
('2017-08-11',2,10000),
('2017-08-15',2,10000),
('2017-09-01',2,10000);
DROP TABLE IF EXISTS table2;
CREATE TABLE table2
(purchase_date DATE NOT NULL
,quantity INT NOT NULL
,price INT NOT NULL
);
INSERT INTO table2 VALUES
('2017-08-21',1,10000);
SELECT DATE_FORMAT(purchase_date,'%Y-%m') yearmonth
, SUM(quantity*price) total
FROM
(
SELECT * FROM table1
UNION
SELECT * FROM table2
) x
GROUP
BY yearmonth;
+-----------+-------+
| yearmonth | total |
+-----------+-------+
| 2017-08 | 60000 |
| 2017-09 | 20000 |
+-----------+-------+