MYSQL Need first buy code with customer totals - mysql

The Select below summarizes the customer totals, but I need the customers first buy code to show where they first came from.
Select is:
SELECT h.buycode, Min(h.sdate) AS firstBuy, h.i_id,a.eid,count(*) AS orders,Sum(h.i_total) AS revenue,Max(h.sdate) AS LastBuy, a.eid, a.c_id
FROM mk_adr a
INNER JOIN oe_hdr h
ON h.c_id = a.c_id
WHERE h.sdate is not null
GROUP BY a.eid
eid is the enterprise ID that ties all of the c_id's(customer_id) together. A customer can have multiple c_id's, but only 1 eid. Eid is not part of the table oe_hdr.
I've tried using a sub-select with a left join and min(sdate) on oe_hdr, buycode, but it mostly returns null values for buycode.

This may not be the best way, but you can create a table that only holds the first purchase for the user. it places a foreign key to the user, and to the first item that they bought. Then you can just select from that table.
LOGIC:
IF -the user has no buys in the table- THEN
-Place the information in the first buy table-

Related

Group recursive 1:M relationship

I have a table with a recursive 1:M
Every customer may have been referred by a previous customer, now I want to group the customers who have made referrals, so I can display which ones have referred the most.
and I would want a query which gave following output
I tried
SELECT count(*) AS Count_of_referrals, referral_id
FROM Customer
GROUP BY referral_id
which gives the amount of times each referral_id is mentioned, but I can't find a way to link this back to the actual customer who referred them.
Appreciate any help I can get here.. :-)
Well, you're close. You just need to self join the customer table to get the name of the referral_id in there.
SELECT c1.referral_id,
c2.name,
count(*) count_of_referrals
FROM customer c1
INNER JOIN customer c2
ON c2.customer_id = c1.referral_id
GROUP BY c1.referral_id,
c2.name;

MySQL - How do I select most recent row for a particular user ID, based on the product type purchased (in a query that wont take too long to run)?

I have two tables in a database I'm trying to run a query on:
Table 1 contains the product ID and the type of product it is (e.g. product IDs 1 & 2 are 'lawnmowers', product IDs 3 & 4 are 'leafblowers')
Table 2 contains the user purchases, which has a product ID column (but not product type). Product ID corresponds to the first table. Each user has the same user_ID across multiple purchases, but also a unique purchase ID.
I am trying to run a query on product types (e.g. lawnmower), to get all of the people who bought lawnmowers, and then remove duplicates for people who bought multiple lawnmowers (I want only the latest purchase for each person). So I want to filter by user_id and only use the maximum value for purchase id (the latest one).
This is where I'm at so far with the query - it's currently not running as I think it's taking too long (I'm not getting any syntax errors):
SELECT *
FROM purchases
WHERE product_id IN (
SELECT product_id
FROM [database_name].products
WHERE product_type="lawnmowers"
)
AND purchase_id IN (
SELECT MAX(puchase_id)
FROM purchases
GROUP BY user_id
)
Does anyone know an alternative query that will run a bit faster and will achieve the results I'm after?
I think you just want this query. Try joining the purchases table to a subquery which identifies the latest lawnmower purchase, for each user.
SELECT *
FROM purchases t1
INNER JOIN
(
SELECT p1.user_id, MAX(p1.purchase_id) AS max_purchase_id
FROM purchases p1
INNER JOIN products p2
ON p1.product_id = p2.product_id
WHERE p2.product_type = 'lawnmowers'
GROUP BY p1.user_id
) t2
ON t1.user_id = t2.user_id AND t1.purchase_id = t2.max_purchase_id;
Note that while this should return the latest lawnmower purchase for each user, it won't report users who never made a lawnmower purchase. If you have the requirement to report on all users, then you should probably have a separate user table which can be used for joining here.

Calculate in SQL with Inner Join

I am trying to calculate in a SQL statement. I am trying to calculate the total amount in the invoice.total column per customer. I created the following statement:
SELECT customers.firstname, customers.lastname, customers.status, SUM(invoice.total) AS total
FROM customers
INNER JOIN invoice
ON customers.id=invoice.id;
When I run this, I get the total amount in the table. I have 15 different customers in this table but I get only the name of the first customer and the total amount of all customers. What am I doing wrong?
First, you need to Group the data when you want to have aggregate results:
SELECT customers.firstname, customers.lastname, customers.status, SUM(invoice.total) AS total
FROM customers
INNER JOIN invoice
ON customers.id=invoice.id
GROUP BY customers.firstname, customers.lastname, customers.status;
Second, are you sure you are joining the table by correct fields? Is invoice.id correct column? I would expect invoice.id to be primary key for the table and instead I would expect another column for foreign key, invoice.customerid for example. Please double check it is correct.
UPDATE: As it was mentioned in comments, if you have two customers with same first name, last name and status, the data will be grouped incorrectly. In that case you need to add unique field (e.g. customers.id) to SELECT and GROUP BY statements.
You have to add a group by customer (id property for example). If you want to have first and last name in select then you will have to group by them as well.
Use group by clause in your query or you can use common table expression to get the sum of records by customer and then make a inner join with customer table.
You need to add a Group By with column names in your query.

Creating an SQL View With Calculations From Multiple Tables

So I have two tables that I need information from. I have a
ballot_table(vote CHAR(30), username CHAR(30)) that has the name of the candidate each username voted for. I also have another table with a list of the candidates. I need someway to return the list of candidates with the corresponding amount of times there name appears in ballot_table in the same query. Thanks!
This is a horrible design but here is how you do it:
select count(*) as votes, vote as [candidate]
from ballot_table
where ucase(vote) in (select ucase(item) from table_with_list_of_candidates)
group by ucase(vote)
a better design would have the list of candidates table include a key and then just have the key in the ballot_table with a varchar for a write in (if needed).
You can do this with an Outer Join and a Group By. I'm assuming the field name in the candidate table is Name.
Select c.Name, Count(Distinct b.UserName) Votes
From ballot_table b
Right Join candidate c On c.Name = b.Vote
Group By c.Name
This would only return the total votes for the candidates you have in your Candidate table. Any other "write-in" vote wouldn't be included.

How can I grab information in MySQL via 2 foreign keys going to the same table?

I have a table called sales with two columns vendor_id and customer_id. Both are id's to a row in the people table. I want to grab a sales row by it's id and get the customer name and the vendor name.
How can I do this with MySQL?
Join your people table twice to the sales table (you'll need to alias it at least one time in order to avoid a name collision):
SELECT customer.name AS customer_name, vendor.name AS vendor_name
FROM sales
JOIN people AS customer ON customer.id = sales.customer_id
JOIN people AS vendor ON vendor.id = sales.vendor_id
WHERE sales.id = ?