I have two tables customers and orders, where important columns are:
/* Customers: */
id | login | membershipid
100 | email1 | 0
101 | email2 | 0
/* Orders: */
userid | total
100 | 150
101 | 120
101 | 450
I want to update membershipid depending of total purchases for each customer. Lets say it will be zero if the sum is less than 500, one if sum is 500-1000, two if sum is over 1000.
I get the sum this way:
SELECT customers.login, sum( orders.total ) AS total_purchased
FROM xcart_customers AS customers
LEFT JOIN xcart_orders AS orders ON customers.id = orders.userid
GROUP BY customers.login
but I am not sure how to update back customers table. Something like:
UPDATE xcart_customers set (membershipid) = (
SELECT sum( orders.total ) AS total_purchased
FROM xcart_customers AS customers
LEFT JOIN xcart_orders AS orders ON customers.id = orders.userid
GROUP BY customers.login
)
but where and how to use conditions (and will GROUP BY work?):
CASE
WHEN
..
ELSE
END
UPDATE xcart_customers
join
(
SELECT customers.login, sum( orders.total ) AS total_purchased
FROM xcart_customers AS customers
LEFT JOIN xcart_orders AS orders ON customers.id = orders.userid
GROUP BY customers.login
) tmp on tmp.login = xcart_customers.login
set xcart_customers.membershipid = case when total_purchased is null or total_purchased < 500 then 0
when total_purchased between 500 and 1000 then 1
else 2
end
One way to do this is with a join operation. Take your query, and turn it into an inline view, and join that back to the customers table.
We might want to handle the case when total_purchased is NULL as being less than 500 (when a customer doesn't have any related rows in xcart_orders.)
As a SELECT it would look like this:
SELECT t.login
, t.membershipid
, CASE
WHEN IFNULL(s.total_purchased,0) < 500 THEN 0
WHEN s.total_purchased <= 1000 THEN 1
WHEN s.total_purchased > 1000 THEN 2
ELSE NULL
END AS new_membershipid
FROM customers t
JOIN ( SELECT c.login
, SUM(o.total) AS total_purchased
FROM xcart_customers c
LEFT
JOIN xcart_orders o
ON o.userid = c.id
GROUP BY c.login
) s
ON s.login = t.login
To convert that into an UPDATE, replace the SELECT ... FROM with UPDATE
and add a SET clause at the end of the statement (before the WHERE clause if there was a WHERE clause).
For example:
UPDATE customers t
JOIN ( SELECT c.login
, SUM(o.total) AS total_purchased
FROM xcart_customers c
LEFT
JOIN xcart_orders o
ON o.userid = c.id
GROUP BY c.login
) s
ON s.login = t.login
SET t.membershipid =
CASE
WHEN IFNULL(s.total_purchased,0) < 500 THEN 0
WHEN s.total_purchased <= 1000 THEN 1
WHEN s.total_purchased > 1000 THEN 2
ELSE NULL
END
NOTE: This assumes that login is UNIQUE` in the customers table.
FOLLOWUP
Given that membershipid cannot be assigned a NULL value, we can tweak the CASE expression. Do the check for > 1000 first, then a check for >= 500, else 0.
For example:
CASE
WHEN s.total_purchased > 1000 THEN 2
WHEN s.total_purchased >= 500 THEN 1
ELSE 0
END
Related
i need a query that should first look the oldest order which has status 0 (zero). and retrieves all the similar orders of that kind(matches exact total qty, itemSku and number of distinct items ordered).
***OrdersTable***
ID OrderNumber CustomerId Status created_at
1 123456 1 0 2018-01-01
2 234567 1 0 2018-01-02
3 345678 1 0 2018-01-03
4 456789 1 0 2018-01-04
***PurchasedProductsTable***
OrderId itemSku Qty
1 1000001 1
1 1000002 2
2 1000001 3
3 1000001 1
3 1000002 2
4 1000001 3
In the above table the query should first look at the oldest (created_at ASC) order (i.e with Id 1) having status 0 (in order table). and along with that order it should retrieves all the other orders that matches the same itemSku, qty and total distinct items count (in purchasedProducts table).
here order 1 and 3 matches the same itemSKu (1000001 and 1000002) and qty ( 1 and 2) and both have (2) distinct items count respectively so order 1 and 3 should be retrived at first.and when i marked order 1 and 3 as shipped (i.e chang status to 2).
and if i run query again it should retrive similar oders. now order 2 and 4 as order 2 and 4 are similar orders. (have same itemSkus (1000001, Qty (3) and distinct items count (1)).
please help thanks
You have to go trough your tables two times :)
Something like this :
SELECT DISTINCT O2.ID
FROM OrdersTable O1
INNER JOIN PurchasedProductsTable P1 ON O1.ID = P1.OrderId
INNER JOIN PurchasedProductsTable P2 ON P1.itemSku = P2.itemSku
AND P1.Qty = P2.Qty
INNER JOIN OrdersTable O2 ON O2.ID = P2.OrderId
WHERE O1.ID =
(SELECT ID FROM OrdersTable WHERE Status = 0
ORDER BY created_at ASC LIMIT 1)
AND (SELECT COUNT(*) FROM PurchasedProductsTable WHERE OrderId = O1.ID)
= (SELECT COUNT(*) FROM PurchasedProductsTable WHERE OrderId = O2.ID)
ORDER BY O2.ID ASC;
https://www.db-fiddle.com/f/65t9GgSfqMpzNVgnrJp2TR/2
You can get the earliest order via a limit and ordered by the date.
Then you can left join to get that order and any other order that at least has the same items.
Then once you have those order id's from the sub-query result, you can get the order details.
SELECT o.*
FROM
(
SELECT DISTINCT ord2.ID as OrderId
FROM
(
SELECT ID, CustomerId, Status
FROM OrdersTable
WHERE Status = 0
ORDER BY created_at
LIMIT 1
) AS ord1
JOIN PurchasedProductsTable AS pprod1
ON pprod1.OrderId = ord1.ID
LEFT JOIN OrdersTable ord2
ON ord2.CustomerId = ord1.CustomerId
AND ord2.Status = ord1.Status
LEFT JOIN PurchasedProductsTable pprod2
ON pprod2.OrderId = ord2.ID
AND pprod2.itemSku = pprod1.itemSku
AND pprod2.Qty = pprod1.Qty
GROUP BY ord1.CustomerId, ord1.ID, ord2.ID
HAVING COUNT(pprod1.itemSku) = COUNT(pprod2.itemSku)
) q
JOIN OrdersTable AS o ON o.ID = q.OrderId;
Test on RexTester here
I have the following tables, for example:
invoices
ID Name
1 A
2 B
3 C
4 D
5 E
transactions
ID Invoice_ID User_ID
1 1 10
2 1 10
3 1 10
4 2 30
5 3 20
6 3 40
7 2 30
8 2 30
9 4 40
10 3 50
Now I want to make a select that will pull the invoices and the user_id from the related transactions, but of course if I do that I won't get all the ids, since they may be distinct but there will be only one column for that. What I want to do is that if there are distinct User_ids, I will display a pre-defined text in the column instead of the actual result.
select invoices.id, invoices.name, transactions.user_id(if there are distinct user_ids -> return null)
from invoices
left join transactions on invoices.id = transactions.invoice_id
and then this would be the result
ID Name User_ID
1 A 10
2 B 30
3 C null
4 D 40
5 E null
Is this possible?
You can do the following :
select
invoices.id,
invoices.name,
IF (
(SELECT COUNT(DISTINCT user_id) FROM transactions WHERE transactions.invoice_id = invoices.id) = 1,
(SELECT MAX(user_id) FROM transactions WHERE transactions.invoice_id = invoices.id),
null
) AS user_id
from invoices
Or, alternatively, you can use the GROUP_CONCAT function to output a comma-separated list of users for each invoice. It is not exactly what you asked, but maybe in fact it will be more useful :
select
invoices.id,
invoices.name,
GROUP_CONCAT(DISTINCT transactions.user_id SEPARATOR ',') AS user_ids
from invoices
left join transactions on invoices.id = transactions.invoice_id
group by invoices.id
Try somethingh like:
select i.id, i.name, t.user_id
from invoices i left join
(
select invoice_ID, User_ID
from transactions
group by invoice_ID
having count(invoice_ID)=1
) t on i.id=t.invoice_id
SQL fiddle
You could list all the transactions that have multiple user ids, like this:
select invoices.id, invoices.name, null
from invoices
left join transactions on invoices.id = transactions.invoice_id having count(distinct transactions.user_id) > 1
Also, I think this CASE might suit your needs here:
select invoices.id, invoices.name,
case when count(distinct transactions.user_id) > 1 then null else transactions.user_id end
from invoices
left join transactions on invoices.id = transactions.invoice_id
group by invoices.id
although, I'm not sure this is syntactically correct
I have a table setup like this
Liabilities:
Id | CustomerId | liabilities
---------------------------
9 90 1000
...
Payments:
Id | CustomerId | Payment
---------------------------
3 90 2500
4 91 1000
...
Customer:
Id | balance
---------------------------
90 1500
91 1000
...
As you can see, the balance for a customer is the sum of all its payments minus the sum of all its liabilities. What is an SQL query to update the balance?
You can do it using an UPDATE statement with LEFT JOIN operations to derived tables containing Payments and Liabilities aggregates:
UPDATE Customer AS c
LEFT JOIN (
SELECT CustomerId, SUM(Payment) AS TotalPayment
FROM Payments
GROUP BY CustomerId
) AS p ON c.Id = p.CustomerId
LEFT JOIN (
SELECT CustomerId, SUM(liabilities) AS TotalLiabilities
FROM Liabilities
GROUP BY CustomerId
) AS l ON c.Id = l.CustomerId
SET balance = COALESCE(TotalPayment, 0) - COALESCE(TotalLiabilities, 0)
Demo here
Alternatively, you can use correlated subqueries in the UPDATE statement:
UPDATE Customer AS c
SET balance = COALESCE((SELECT SUM(Payment)
FROM Payments
WHERE CustomerId = c.Id) , 0)
-
COALESCE((SELECT SUM(liabilities)
FROM Liabilities
WHERE CustomerId = c.Id) , 0)
Demo here
I've got a database table with logs which has 3 columns:
date | status | projectId
status can be either 0 or 1, primary key is on date and projectID
I'm trying to find out how many times a projectID had status 0 since the last time it was 1.
so if there would be only one projectId
date | status | projectId
1 0 3
2 0 3
3 1 3
4 1 3
5 0 3
6 0 3
this should return 2 (row 5 and 6 are 0 and row 4 is 1)
The thing that makes it hard for me is that I have to maintain the order of date. What would be a good way to tackle such problems, and this one in particular?
Here is how you would do it for one project:
select count(*)
from logs l
where status = 0 and
projectid = 3 and
date > (select max(date) from logs where projectid = 3 and status = 1)
Here is how you would do it for all projects:
select l.projectId, count(l1.projectId)
from logs l left outer join
(select projectId, max(date) as maxdate
from logs
where status = 1
group by projectId
) l1
on l.projectId = l1.projectId and
l.date > l1.date and
l.status = 0
group by l.projectId;
here you have an option in just one select.
http://sqlfiddle.com/#!2/6ce87/11
select *
from logs
where status=0 and date > (select date from logs where status=1 order by date desc limit 1)
Here's one way to get the result for all project_id:
SELECT m.project_id
, COUNT(1) AS mycount
FROM ( SELECT l.project_id
, MAX(l.date) AS latest_date
FROM mytable l
WHERE l.status = 1
) m
JOIN mytable t
ON t.project_id = m.project_id
AND t.date > m.latest_date
AND t.status = 0
If you need only a subset of project_id, the predicate should be added to the WHERE clause in the inline view query:
WHERE l.status = 1
AND l.project_id IN (3,5,7)
EDIT
That query does not return a row if there is no status=0 row after the latest status=1 row. To return a zero count, this could be done with an outer join.
SELECT m.project_id
, COUNT(t.status) AS mycount
FROM ( SELECT l.project_id
, MAX(l.date) AS latest_date
FROM mytable l
WHERE l.status = 1
AND l.project_id IN (3)
) m
LEFT
JOIN mytable t
ON t.project_id = m.project_id
AND t.date > m.latest_date
AND t.status = 0
For optimum performance, the statement could make use of an index with leading columns of project_id and date (in that order) and including the status column, e.g.
ON mytable (`project_id`,`date`,`status`)
I have a couple of tables:
Invoice
-----------------
ID total
1 500.00
2 100.00
3 10.00
Payment
---------------------------------------
ID invoiceId Amount Method
1 1 400 CASH
2 2 60 CASH
3 2 40 CREDIT
I need a query that gets all invoices where at least one payment.method is CREDIT and the sum of all payments for that invoice is greater than the total of the invoice.
And I need it to be fast.
How can I do this?
SELECT a.ID InvoiceID,
a.Total TotalInvoice,
b.TotalPayment
FROM Invoice a
INNER JOIN
(
SELECT InvoiceID, SUM(Amount) TotalPayment
FROM Payment
GROUP BY InvoiceID
HAVING SUM(Method = 'CREDIT') > 0
) b ON a.ID = b.InvoiceID AND
a.Total < b.TotalPayment
SQLFiddle Demo
Another method:
SELECT
i.`id`,
i.`total` AS `total_invoiced`,
SUM(p.`amount`) AS `total_payments`,
SUM(IF(p.`method`='credit', 1, 0)) AS `count_credit`
FROM `invoices` i
LEFT JOIN `payments` p ON (p.`invoice_id`=i.`id`)
WHERE 1=1
GROUP BY i.`id`
HAVING (`total_payments` > i.`total`) AND (`count_credit` > 0)
I changed some table/field names. Sorry for the inconvenience.
http://www.sqlfiddle.com/#!2/7402d/1/0
try this one:
select iagg.ID
from (
select i.ID
, sum (p.amount) tl_paid
, min (i.total) tl
from invoice i
join payment p on ( p.invoiceID = i.ID )
group by i.ID
) iagg
where exists (
select 1
from payment p2
where p2.invoiceId = iagg.ID
and p2.method = 'CREDIT'
)
and iagg.tl_paid > iagg.tl
;
the minimum operator over the total attribute is mandated by the grouping operator, the minimum is actually taken from a set of identical values.