I am trying to do a regular join but select the latest entry from the history_items table using a where clause.
SELECT h.history_id,
Date_format(From_unixtime(h.timestamp), '%d %m %Y') AS 'date',
h.status,
h.product_id,
p.serial_number,
p.product_name,
p.site_name,
p.site_postcode,
Date_format(From_unixtime(i.timestamp), '%d %m %Y') AS 'last_update',
i.feedback
FROM history h
LEFT JOIN products p
ON h.product_id = p.product_id
LEFT JOIN history_items i
ON h.history_id = i.history_id
WHERE i.timestamp = (SELECT Max(i.timestamp)
FROM history_items)
GROUP BY i.history_id
ORDER BY h.timestamp DESC
I am selecting Max(i.timestamp) - this is still not returning the latest entry from the history_items table.
I think your problem is here:
WHERE i.timestamp = (SELECT Max(i.timestamp)
FROM history_items)
The i should not be there, it should be Max(timestamp) not Max(i.timestamp).
Else Mysql will really select the value of the i.timestamp row. So if your timestamp is 1 it will evaluate to this:
WHERE 1 =(SELECT Max(1) FROM hsitory_items)
Which basically will be
WHERE i.timestamp = i.timestamp
I bet you get the idea now. That's why all rows are returned.
Since you are anyways sorting on timestamp saying ORDER BY h.timestamp DESC you actually don't need the below pointed WHERE condition at all. Also the subquery in below pointed code is wrongly referring the column as already mentioned in other answer
WHERE i.timestamp = (SELECT Max(i.timestamp)
FROM history_items)
Related
I have
select created_at, sales_flat_order.customer_id,
customer_firstname, customer_lastname, customer_email,
sales_flat_order_address.company,
SUM(grand_total)
from sales_flat_order
left join sales_flat_order_address
on sales_flat_order.entity_id = sales_flat_order_address.entity_id
where created_at >= '2016-06-01 05:00:00' /* 5h difference */
and store_id = 1
and `status` = 'Complete'/*
left join customer_entity
on sales_flat_order.customer_id = customer_entity.entity_id*/
group by customer_email;
Runs fine. Comment content produces error with SQL syntax, code 1064. What's the problem?
Same issue now with this:
select customer.entity_id, customer.group_id,
customer.created_at,
sfo.customer_firstname, sfo.customer_lastname,
sfo.customer_email,
sfo.created_at last_order,
count(sfo.customer_id) num_orders,
group_concat(sfo.grand_total separator '|') grand_totals
from customer_entity customer
inner join sales_flat_order sfo
on customer.entity_id = sfo.customer_id
where sfo.created_at >= '2016-06-01 05:00:00'
and sfo.store_id = 1
and sfo.`status` = 'Complete'
left outer join customer_group
on customer.group_id = customer.customer_group_id
where customer_group.customer_group_id
group by customer.entity_id;
Thanks everyone, that all makes ample sense, definitely getting into the hang of it; how's this? It works but tear it up if anything remains amuck.
select customer.entity_id, customer.group_id, `group`.customer_group_code,
customer.created_at,
`order`.customer_firstname, `order`.customer_lastname,
`order`.customer_email, address.company,
`order`.created_at last_order,
count(`order`.customer_id) num_orders,
group_concat(`order`.grand_total separator '|') grand_totals
from customer_entity customer
inner join sales_flat_order `order`
on customer.entity_id = `order`.customer_id
left outer join customer_group `group`
on customer.group_id = `group`.customer_group_id
left outer join sales_flat_order_address address
on `order`.entity_id = address.entity_id
where `order`.created_at >= '2016-06-01 05:00:00'
and `order`.store_id = 1
and `order`.`status` = 'Complete'
group by customer.entity_id;
I know everyone said to add to the group by clause but there is nothing else I want to group by...?
The where clause must be after all of the joins. There are other issues as well, but that's the issue that really breaks things.
If it were me, I'd also fix the group by clause to match the select list, but MySql lets you write non-standard SQL in this way. You may also have a naming conflict when you add the additional table because you haven't qualified the column names. Aliases would make this easier to do Finally, it's possible for your query logic that you want some of the conditional expressions in the where clause to be part of the first ON clause.
If you format your code properly, it's easy to see why your code doesn't work. Your commented LEFT JOIN that caused the error is after the WHERE clause. Also write proper SQL. Alias your table name because long column names are annoying. Put all non-aggregated columns in the GROUP BY clause. Your code won't even run in any other dbms except for maybe MySQL.
select created_at, sales_flat_order.customer_id
, customer_firstname, customer_lastname
, customer_email
, sales_flat_order_address.company
, SUM(grand_total)
from sales_flat_order
left join sales_flat_order_address on sales_flat_order.entity_id = sales_flat_order_address.entity_id
where created_at >= '2016-06-01 05:00:00' /* 5h difference */
and store_id = 1
and `status` = 'Complete'/*
left join customer_entity on sales_flat_order.customer_id = customer_entity.entity_id*/
group by customer_email;
I am looking for how many number of columns I can use in "order by" clause, for e.g. I have a column NAME asc, START_DATE asc, SKU_GROUP asc and want to add SKU_NAME asc in order clause. I am currently using 1 group by but for curiosity how many can be used within MySQL?
SELECT pop.SUB_ELEMENT, pop.NAME, sub_element.LDESC AS SUB_NAME, DATE_FORMAT(journey_visits.START_DATE, '%b %d %Y %h:%i %p' ) AS START_DATE, visit_sku.IS_CHECK,visit_sku.TYPE AS `SKU_TYPE`,brand.LDESC AS `SKU_GROUP`,sku.LDESC AS `SKU_NAME`,sku.SKU AS `MATERIAL` FROM visit_sku
LEFT JOIN journey_visits ON journey_visits.VISIT_ID = visit_sku.VISIT_ID
LEFT JOIN pop ON journey_visits.POP_ID = pop.POPID
LEFT JOIN sub_element ON sub_element.SubElementID=pop.SUB_ELEMENT
LEFT JOIN sku ON visit_sku.SKU_ID = visit_sku.SKU_ID AND visit_sku.SKU_ID = sku.SKU
LEFT JOIN brand ON sku.brandid = brand.BRANDID
WHERE DATE(journey_visits.START_DATE) BETWEEN '2016-04-01' AND '2016-04-03'
ORDER BY NAME, START_DATE, SKU_NAME
There is no limit, you can order by or group by all columns in a result set, although the latter would be useless.
SELECt
qst_id,qst_title,ans_date,ans_text
FROM
(
SELECT
a.Question_Id as qst_id,a.Question_Title as qst_title,a.Question_Text as qst_text,DATE_FORMAT(a.LastActivity_Date,'%d %b %Y %T') as qst_date,b.UserForum_Image as qst_prof,b.ScreenName as qst_scname
FROM
tblforumquestion a, tblregistration2_2 b
WHERE a.RegistrationId=b.RegistrationId and a.LastActivity_Date between '2014-0-01 00:00:00' and '2015-05-01 00:00:00'
ORDER BY a.LastActivity_Date desc limit 5
outer join
SELECT
DATE_FORMAT(c.Answer_Date,'%d %b %Y %T') as ans_date,c.Answer_Text as ans_text,d.UserForum_Image as ans_prof,d.ScreenName as ans_scname
FROM
tblforumanswer c ,tblregistration2_2 d
where c.Answer_Id in
(
SELECT MAX(Answer_Id)
FROM tblforumanswer
GROUP BY Question_Id
)
and c.RegistrationId=d.RegistrationId
order by c.Answer_Date desc limit 5
)
I am trying to get latest 5 question and answers from my post.if any question without answer is there,it should also display as question details in one row with null answer details.But the above code is getting error.Any help is appreciable.my database is mysql.
tblquest
tblans
result
I think we've finally extracted enough detail to arrive at an answer:
select q.qstid, q.qsttext, a.anstext
from tblquest q
left join tblans a
on q.qstid = a.qstid
left join tblans a2
on a.qstid = a2.qstid and a.ansdate < a2.ansdate
where a2.ansdate is null
order by q.qdate desc limit 5;
demo here
We left join the answers to the questions, in order to ensure we have keep all questions, including those without answers.
We then left join to the answers again, but this time on a range condition in order to just pick off the most recent answer to the question. If there is no a2 with a date greater than a, then that a must be the most recent answer - this is filtered for by the where a2.ansdate is null clause.
That could also be accomplished with a subquery if you preferred.
Finally, we just order and limit our results in order to get the 5 most recent questions.
Problem with your outer join syntax. Check the comment and sample data.
SELECT
qst_id,qst_title,ans_date,ans_text
FROM
(
SELECT
a.Question_Id as qst_id,a.Question_Title as qst_title,a.Question_Text as qst_text,DATE_FORMAT(a.LastActivity_Date,'%d %b %Y %T') as qst_date,b.UserForum_Image as qst_prof,b.ScreenName as qst_scname
FROM
tblforumquestion a, tblregistration2_2 b
WHERE a.RegistrationId=b.RegistrationId and a.LastActivity_Date between '2014-0-01 00:00:00' and '2015-05-01 00:00:00'
ORDER BY a.LastActivity_Date desc limit 5
outer join --Error comes here
SELECT
DATE_FORMAT(c.Answer_Date,'%d %b %Y %T') as ans_date,c.Answer_Text as ans_text,d.UserForum_Image as ans_prof,d.ScreenName as ans_scname
FROM
tblforumanswer c ,tblregistration2_2 d
where c.Answer_Id in
(
SELECT MAX(Answer_Id)
FROM tblforumanswer
GROUP BY Question_Id
)
and c.RegistrationId=d.RegistrationId
order by c.Answer_Date desc limit 5
)
--This is example of outer join
SELECT
A.*, B.*
FROM
TableA a outer join TableB b on a.RegistrationId = b.RegistrationId
Refer link for more detail:
Full Outer Join in MySQL
https://dev.mysql.com/doc/refman/5.0/en/outer-join-simplification.html
http://www.w3schools.com/sql/sql_join_full.asp
I am trying to find the number of records for current week.
My current query is:
SELECT Week(Str_to_date(products_options_values, '%m-%d-%Y'), 1) AS order_week,
Year(Str_to_date(products_options_values, '%m-%d-%Y')) AS order_year,
order_active,
Count(op.sub_order_id) AS deliveries
FROM orders_products_attributes opa
LEFT JOIN orders_products op
ON ( opa.orders_products_id = op.orders_products_id )
GROUP BY order_week,
order_year
HAVING order_week = '31'
AND order_year >= '2013'
AND order_active = 0
ORDER BY order_week
It fetches deliveries AS 2 where as there are actually 4 records, and if I run the same query after removing COUNT and GROUP BY, it correctly shows all 4 rows. The same problem happens on other weeks too, for example week 34 has 3 records, but the above query fetches it as 4 instead. Moreover, another weird thing is, in the GROUP BY clause, if I remove either one of order_week or order_year the query returns an empty result set.
Any idea what I am doing wrong?
Try to move all HAVING conditions into WHERE. Also Count(id) - counts UNIQUE values of ID not all. If you need all records count just use COUNT(*)
SELECT Week(Str_to_date(products_options_values, '%m-%d-%Y'), 1) AS order_week,
Year(Str_to_date(products_options_values, '%m-%d-%Y')) AS order_year,
order_active,
Count(op.sub_order_id) AS deliveries
FROM orders_products_attributes opa
LEFT JOIN orders_products op
ON ( opa.orders_products_id = op.orders_products_id )
WHERE order_week = '31'
AND order_year >= '2013'
AND order_active = 0
GROUP BY order_week,
order_year
ORDER BY order_week
So I am trying to alter my sql code (see below for screenshot of current results + sql) to group the data by the month AND sum up all the paymentSplitAmounts. Each row should be a unique productId
So the end result would be something like
productID total month
1 500 11-2011
2 650 11-2011
3 250 11-2011
1 100 10-2011
2 150 10-2011
3 750 10-2011
I can't seem to get the syntax right. Where am I going wrong?
http://imgur.com/UC5Si
select
cpd.paymentId, cpd.paymentId, cpd.productId, cpd.paymentSplitAmount, cp.campaignId, cp.paymentDate
from campaign_payment_detail cpd
inner join
campaign_payment cp on cp.paymentId = cpd.paymentId
inner join product on cpd.productId = product.productId
where
1=1
and cp.campaignId = 2413
Looks like you want to group then sort your results:
SELECT cpd.productId, SUM(cpd.paymentSplitAmount), DATE_FORMAT(cp.paymentDate, '%b-%Y')
FROM campaign_payment_detail cpd
JOIN campaign_payment cp ON cp.paymentId = cpd.paymentId
JOIN product ON cpd.productId = product.productId
WHERE cp.campaignId = 2413
GROUP BY cpd.productId, DATE_FORMAT(cp.paymentDate, '%b-%Y')
ORDER BY cp.paymentDate DESC, cpd.productId ASC
edit: Using DATE_FORMAT to format the date like you want.
First, based on the query you provided and without other information, the table product is useless..
I will do that:
select
cpd.paymentId,
SUM(cpd.paymentSplitAmount) as total,
cp.campaignId,
cp.paymentDate
from campaign_payment_detail cpd
inner join
campaign_payment cp on cp.paymentId = cpd.paymentId
where
cp.campaignId = 2413
GROUP BY cpd.productId, cp.paymentDate
ORDER BY cpd.paymentId ASC, cp.paymentDate DESC
You already mentioned 'grouping'. For that you need to add group by to your query, to group the data by productid and month, then you can add sum to sum the paymentSplitAmount.
The grouping syntax isn't wrong, it is missing completely. :)
select
cpd.productId, sum(cpd.paymentSplitAmount) as total, date_format(cp.paymentDate, '%m-%Y')
from campaign_payment_detail cpd
inner join campaign_payment cp on cp.paymentId = cpd.paymentId
inner join product on cpd.productId = product.productId
where
cp.campaignId = 2413
group by cp.productId, date_format(cp.paymentDate, '%m-%Y')
order by date_format(cp.paymentDate, '%m-%Y') desc, cp.productId
This assumes cp.paymentDate already contains the months. If not, you will have to round each date to the first of the month and group by that.
Now groups by month.