I have two table.
Table 'customers': customer_id, date_register, name
Table 'orders': order_id, customer_id, order_date
Now I want the customers who have orders before specific date and have NOT after that date.
I am using this query:
SELECT customer_id
FROM orders
WHERE EXISTS (SELECT order_id
FROM orders
WHERE order_date <= '2020-05-12 23:59:59')
AND NOT EXISTS (SELECT order_id
FROM orders
WHERE order_date > '2020-05-12 23:59:59')
But I get empty result.
What SQL query should I use?
You can use aggregation and set the condition in the HAVING clause:
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING MAX(order_date) < '2020-05-13';
You could try selecting the customer based on the two range using main query and a subquery in left join then checking for not matching id
SELECT DISTINCT customer_id
FROM orders
LEFT JOIN
(SELECT DISTINCT customer_id
FROM orders
WHERE order_date > '2020-05-12 23:59:59') t ON t.customer_id = orders.customer_id
AND orders.order_date <= '2020-05-12 23:59:59'
WHERE t.id IS NULL
Related
I am stuck with the following problem: I would like to return from my query the orders which have yet to be paid with the amount of the order and my customer information.
Here is what the tables look like:
Taking the case of customer number 124. I can see that this one has placed 13 orders. But I only have 7 checks registered
And I can see that if I add the sum of the orders minus the sum of the payments I find a difference that corresponds to the last 3 orders that this customer has placed.
So the question is how do I bring out the commands 10382, 10371, 10368 with all that? Knowing that the solution must be able to be applied to all orders.
So I thought to myself maybe using the order and payment dates. What orders does my customer place between their last payment and today?
So I tried something like this
#last order date
WITH last_cmd AS
(
SELECT
customerNumber, od.orderNumber, orderDate last_orderDate,
shippedDate, SUM(quantityOrdered * priceEach) totcmd
FROM
orders o
LEFT JOIN
orderdetails od ON o.orderNumber = od.orderNumber
WHERE
status NOT LIKE 'Can%'
GROUP BY
orderDate
ORDER BY
customerNumber, orderDate DESC
),
#last payment date last_payment AS
(
SELECT
customerNumber, amount, paymentDate, checkNumber
FROM
payments
GROUP BY
paymentDate
ORDER BY
customerNumber, paymentDate DESC
)
SELECT *
FROM last_cmd lc
LEFT JOIN last_payment lp ON lc.customerNumber = lp.customerNumber
GROUP BY lc.orderNumber
HAVING MAX(paymentDate) NOT BETWEEN MAX(last_orderDate) AND NOW();
But as you can see the result is not really what is expected. Still taking customer 124 as an example, command 10382 does not appear. And when I do the comparison of other orders manually for other customers the results do not match.
Does anyone have an idea please?
Here is the query I tried before posting
WITH ALL_PAYMENTS AS (
WITH paymentsValues AS (
select customerNumber, checkNumber, YEAR(paymentDate) paymentYear, sum(amount) paymentValue
from payments
LEFT JOIN customers USING (customerNumber)
GROUP BY customerNumber, paymentYear)
SELECT
customerNumber,
checkNumber, #Cumul des commandes clients
paymentYear,
SUM(paymentValue) totalPaymentsValue
FROM
paymentsValues
GROUP BY
customerNumber,
checkNumber
WITH ROLLUP
HAVING checkNumber is null),
ALL_ORDERS AS(
WITH ordersValues AS (
select customerNumber, orderNumber, YEAR(orderDate) orderYear, sum(quantityOrdered*priceEach) AS orderValue
from orderdetails
LEFT JOIN orders USING (orderNumber)
GROUP BY orderNumber, orderYear)
SELECT
customerNumber,
orderNumber, #Cumul des commandes clients
orderYear,
SUM(orderValue) totalOrderValue
FROM
ordersValues
#where orderNumber = '10179'
GROUP BY
customerNumber,
orderNumber
WITH ROLLUP
HAVING orderNumber is null)
SELECT AO.customerNumber, totalOrderValue, totalPaymentsValue, totalOrderValue-totalPaymentsValue Diff
FROM ALL_ORDERS AO
LEFT JOIN ALL_PAYMENTS AP ON AP.customerNumber=AO.customerNumber
WHERE totalOrderValue-totalPaymentsValue > 0;
This should give a list op amount that have to be paid, per date:
WITH d as (
select distinct orderDate as `date` from orders
union
select distinct paymentDate as `date` from payments)
select
`date`,
`customerNumber`,
`ordersValue`,
`amountPayed`,
`ordersValue` - `amountPayed` NotPayed
from (
select
d.`date` as "date",
o.customerNumber as "customerNumber",
sum(quantityOrders*priceEach) ordersValue,
(select sum(amount)
from payments p
where o.customerNumber = p.customerNumber AND p.paymentDate <= d.`date`) as amountPayed
from orderdetails od
cross join d
inner join Orders o on od.orderNumber = o.orderNumber AND o.orderDate <= d.`date`
group by d.`date`, o.customerNumber
) orderListPerCustomer
WHERE `customerNumber` = 124
ORDER BY `date` DESC
;
It is impossible to add order info, because there is no order info in the payments
This query does not take into account the status of the order (which might be Cancelled)
NOTE: This code is not tested, so there could be typing errors...
Here's my orders table:
I want to select all orders excluding very first order of each customer (if customer has placed multiple orders).
So if a customer e.g. 215 has total 8 orders, then I will select his all last 7 orders excluding his very first order 70000 which was placed on 10 July 2017.
But if a customer e.g. 219 had placed only one order 70007, it must be selected by the query.
Using an anti-join approach:
SELECT o1.order_id, o1.customer_id, o1.order_date, o1.order_value
FROM orders o1
LEFT JOIN
(
SELECT customer_id, MIN(order_date) AS min_order_date, COUNT(*) AS cnt
FROM orders
GROUP BY customer_id
) o2
ON o1.customer_id = o2.customer_id AND
o1.order_date = o2.min_order_date
WHERE
o2.customer_site = 1 AND
(o2.customer_id IS NULL OR
o2.cnt = 1);
The idea here is to try to match each record in orders to a record in the subquery, which contains only first order records, for each customer. If we can't find a match, then such an order record cannot be the first.
You can try below -
select order_id,customer_id,order_date,order_Value
from tablename
group by order_id,customer_id,order_date,order_Value
having count(order_id)=1
union all
select order_id,customer_id,order_date,order_Value
from tablename a where order_date not in (select min(order_date) from tablename b
where a.customer_id=b.customer_id)
Solution
Dear #Tim Biegeleisen, your answer almost done. just add HAVING COUNT(customer_id)>1
So the query is below:
SELECT o1.order_id, o1.customer_id, o1.order_date, o1.order_value
FROM orders o1
LEFT JOIN (
SELECT customer_id, MIN(order_date) AS min_order_date
FROM orders
GROUP BY customer_id
HAVING COUNT(customer_id)>1
) o2
ON o1.customer_id = o2.customer_id AND
o1.order_date = o2.min_order_date
WHERE
o2.customer_id IS NULL;
I am trying to use a subquery to retrieve the oldest order for each customer. I want to select email_address, order_id, and order_date
Tables:
customers(customer_id, email_address)
orders(order_id, order_date, customer_id)
What I've tried:
I can get either the order_id or the order_date by doing
SELECT email_address,
(SELECT order_date /* or order_id */
FROM orders o
WHERE o.customer_id = c.customer_id
ORDER BY order_date LIMIT 1)
FROM customers c
GROUP BY email_address;
but if I try to do SELECT order_id, order_date in my subquery, I get the error:
Operand should contain 1 column(s)
You can solve this with a JOIN, but you need to be careful to only JOIN to the oldest values for a given customer:
SELECT c.email_address, o.order_id, o.order_date
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id AND
o.order_date = (SELECT MIN(order_date) FROM orders o2 WHERE o2.customer_id = c.customer_id)
You could use a JOIN to get the result you want, or modify your query as below:
SELECT email_address,
(SELECT order_date
FROM orders o1
WHERE o1.customer_id = c.customer_id
ORDER BY order_date LIMIT 1) as `order_date`,
(SELECT order_id
FROM orders o2
WHERE o2.customer_id = c.customer_id
ORDER BY order_date LIMIT 1) as `order_id`
FROM customers c
GROUP BY email_address;
The JOIN is of your choice.
How can I select multiple columns from a subquery (in SQL Server) that should have one record (select top 1) for each record in the main query?
SELECT o.order_id, c.email_address, o.order_date
FROM customers c
INNER JOIN (
SELECT order_date, order_id, customer_id
FROM orders o
ORDER BY order_date
) as o on o.customer_id = c.customer_id
GROUP BY email_address;
I have the following query which works perfectly, but only if each select finds a row.
I've attempted to add IFNULL to return 0 if no rows were found but I'm still not getting the correct return.
SELECT IFNULL(paid_value,0)-IFNULL(ordered_value,0)+IFNULL(credit_value,0) AS account_balance
FROM
(
SELECT customer_id, SUM(order_total) AS ordered_value
FROM orders
WHERE customer_id = '1'
GROUP BY customer_id
) AS orders
LEFT JOIN
(
SELECT customer_id, SUM(amount) AS paid_value
FROM transactions
WHERE customer_id = '1'
GROUP BY customer_id
) as payments
ON orders.customer_id = payments.customer_id
LEFT JOIN
(
SELECT customer_id, SUM(amount) AS credit_value
FROM credits
WHERE customer_id = '1'
GROUP BY customer_id
) as credits
ON orders.customer_id = credits.customer_id
This query currently returns empty, it's not returning NULL or 0.
When I run
SELECT customer_id, SUM(order_total) AS ordered_value
FROM orders
WHERE customer_id = '1'
GROUP BY customer_id
It also returns empty, not NULL or 0, unless there's a row. In order for the full query to work, each of the 3 separate queries need to have a row in them.
Any ideas?
It if because none of the columns have a result set, so an empty result set is returned, if you want to always display a row in any case you can try with some tricks like this one for example :
SELECT IFNULL(SUM(payments.paid_value),0)-IFNULL(SUM(orders .ordered_value),0)+IFNULL(SUM(credits.credit_value),0) AS account_balance
FROM
(SELECT 1 AS idx, 0 AS paid_value, 0 AS ordered_value, 0 AS credit_value) a
LEFT JOIN
(
SELECT 1 AS idx, customer_id, SUM(order_total) AS ordered_value
FROM orders
WHERE customer_id = '1'
GROUP BY customer_id
) AS orders
ON a.idx = orders.idx
LEFT JOIN
(
SELECT customer_id, SUM(amount) AS paid_value
FROM transactions
WHERE customer_id = '1'
GROUP BY customer_id
) as payments
ON orders.customer_id = payments.customer_id
LEFT JOIN
(
SELECT customer_id, SUM(amount) AS credit_value
FROM credits
WHERE customer_id = '1'
GROUP BY customer_id
) as credits
ON orders.customer_id = credits.customer_id
GROUP BY a.idx
The example is a proof of concept that can be adapted even to other situations where you need to always returns a row with default values even with no elements in underlying tables .
If you want row event if there is no data available, then I suppose you should either have UNION. Or In this scenario you can include you Customer Table & put each Table on Right Side, make a LEFT JOIN.
I think following select will give you an IDEA.
SELECT O.customer_id, SUM(O.order_total) AS ordered_value
FROM Customers C
left join orders O on C.ID =o.customer_id
WHERE O.customer_id = '1'
GROUP BY O.customer_id
I have an orders table which consists of the following:
id
order_total
delivery_cost
customer_id
I also have a transactions table which has:
id
amount
customer_id
status
What I'm trying to do is,
SELECT SUM(order_total + delivery_cost) FROM orders WHERE customer_id = '1'
then
SELECT SUM(amount) FROM transactions WHERE customer_id = '1' AND transaction_status = 'Paid'
Then with the data, minus the total amount from the order totals.
I've tried different queries using JOINS, but I just can't get my head around it, for example:
SELECT SUM(OrdersTotal - TransactionTotal) as AccountBalance
FROM (
SELECT SUM(`order_total` + `delivery_cost`) FROM `orders` as OrdersTotal
UNION ALL
SELECT SUM(`amount`) FROM `transactions` WHERE `transaction_status` = 'Paid' as TransactionTotal
)
but this didn't work at all. Any help would be greatly appreciated.
The two datasets are effectively autonomous but assuming that it's unlikely to have transactions for a customer without orders, you can acheive your result with a LEFT JOIN rather than a ful outer join - but if you simply join the base tables then you'll likely get values from one table repeated in the interim result set (this is why Joseph B's answer is wrong when a customer has something other than a single row in each table).
SELECT ordered_value-IFNULL(paid_value,0) AS acct_balance
FROM
(
SELECT customer_id, SUM(order_total + delivery_cost) AS ordered_value
FROM orders
WHERE customer_id = '1'
GROUP BY customer_id
) AS orders
LEFT JOIN
(
SELECT customer_id, SUM(amount) AS paid_value
FROM transactions
WHERE customer_id = '1'
AND transaction_status = 'Paid'
FROUP BY customer_id
) as payments
ON orders.customer_id = payments.customer_id
(here the 'GROUP BY' and 'ON' clauses are redundant since your only looking at a single customer - but are required for multiple customers).
Note that calculating a balance based on a sum of transactions is technically correct, it does not scale well - for large systems a better solution (although it breaks the rules of normalization) is to maintain a unified table of transactions and a balance for for the account along with each transaction amount - alternatively use checkpointing.
You can just name the column in your union all query and sum on that:
SELECT SUM(col) as AccountBalance
FROM (SELECT SUM(`order_total` + `delivery_cost`) as col FROM `orders` as OrdersTotal
UNION ALL
SELECT SUM(`amount`) FROM `transactions` WHERE `transaction_status` = 'Paid' as TransactionTotal
) t;
Try this query using a JOIN:
SELECT
SUM(o.order_total + o.delivery_cost) - SUM(t.amount) AS AccountBalance
FROM orders o
INNER JOIN transactions t
ON o.customer_id = t.customer_id AND o.customer_id = '1' AND t.transaction_status = 'Paid';
This should give you the account balance for each customer?
SELECT
ISNULL(o.customer_id, t.customer_id) AS customer_id
OrdersTotal - TransactionTotal AS AccountBalance
FROM (
SELECT
customer_id,
SUM(order_total + delivery_cost) AS OrdersTotal
FROM
orders
GROUP BY
customer_id) o
FULL OUTER JOIN (
SELECT
customer_id,
SUM(amount) AS TransactionTotal
FROM
transactions
WHERE
transaction_status = 'Paid'
GROUP BY
customer_id) t
ON t.customer_id = o.customer_id
You can join the results of your queries and perform your calculations ,note sum without group by will result as one row so the sum in outer query doesn't mean when you have only one row and according to your logic of calculation union has nothing to do with it
SELECT t1.OrdersTotal - t2 .TransactionTotal AS AccountBalance
FROM (
SELECT SUM(order_total + delivery_cost) OrdersTotal ,customer_id
FROM orders
WHERE customer_id = '1'
) t1
JOIN (
SELECT SUM(amount) TransactionTotal ,customer_id
FROM transactions
WHERE customer_id = '1' AND transaction_status = 'Paid'
) t2 USING(customer_id)
Since you are only concerned about a single customer, just have them listed as two different queries as the source...
select
charges.chg - paid.pay as Balance
from
( SELECT SUM(order_total + delivery_cost) chg
FROM orders
WHERE customer_id = '1' ) charges,
( SELECT SUM(amount) pay
FROM transactions
WHERE customer_id = '1' AND transaction_status = 'Paid' ) paid
Now, if you wanted for all customers to see who is outstanding, add the customer's ID to each query and apply a group by, but then change to a LEFT-JOIN so you get all orders with or
select
charges.customer_id,
charges.chg - coalesce( paid.pay, 0 ) as Balance
from
( SELECT customer_id, SUM(order_total + delivery_cost) chg
FROM orders
group by customer_id ) charges
LEFT JOIN ( SELECT customer_id, SUM(amount) pay
FROM transactions
where transaction_status = 'Paid'
group by customer_id ) paid
on charges.customer_id = paid.customer_id
I think this works best if you try an inline view. In the code block below, check the Group By clause, you might need to add more fields in the Group By depending on what you're selecting in the Inner SELECT statements.Try the code below:
SELECT
SUM(Totals.OrdersTotal-Totals.TransactionTotal)
FROM
(SELECT
SUM(ord.order_total + ord.delivery_cost) AS OrdersTotal
, SUM(trans.amount) AS TransactionTotal
FROM orders ord
INNER JOIN transactions trans
ON ord.customer_id = trans.customer_id
WHERE
ord.customer_id =1
AND trans.transaction_status = 'Paid'
GROUP BY
ord.customer_id
) Totals;