How to distinct limit for every data - mysql

Accept my best wishes dear friends, I have a problem related with mysql table. Actually I've a table like this
Now I want to query last purchase tax for every product code. for this i use this mysql query :
SELECT DISTINCT PROD_CODE, PURCHASE_TAX
FROM PRODUCT_STOCK
WHERE PROD_CODE
IN ( 5300, 'BLUEBOOK' )
ORDER BY ID DESC
LIMIT 0 , 30
from doing this mysql returning result set like this
As you can see in result set mysql return all row of related product. while i want only last row. Please help me for this

Since I see no column to show time, I am assume all the records are inserted in serial order, hence greater the id, the more recent the record is.
SELECT DISTINCT(PROD_CODE) AS CODE, (SELECT PRODUCT_STOCK.PURCHASE_TAX FROM PRODUCT_STOCK WHERE PRODUCT_STOCK.PROD_CODE = CODE ORDER BY ID DESC LIMIT 1) AS PURCHASE_TAX
FROM PRODUCT_STOCK
WHERE PROD_CODE
IN ( 5300, 'BLUEBOOK' );

Try with GROUP BY like this
SELECT DISTINCT PROD_CODE, PURCHASE_TAX
FROM PRODUCT_STOCK
WHERE PROD_CODE
IN ( 5300, 'BLUEBOOK' )
GROUP BY PROD_CODE;

Related

want to return latest records where results are grouped by

I'm grouping results by SERIAL_NUMBER and I'd like to display the last records for each group according to record ID DESC this what I've got so far:
SELECT * FROM
(SELECT `SERIAL_NUMBER`, `PART_NUMBER` , `POSITION` , `DUE_CAP_CHECK_DATE` , `DUE_OVERHAUL_DATE`
FROM `history_card` ORDER BY `HISTORY_ID` DESC ) AS X
GROUP BY `SERIAL_NUMBER`
But It does not return the last record, it returns the first one ;(
You are misusing the heinously confusing nonstandard MySQL extension to GROUP BY. Read this. https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html (This extension is like a talking horse. We don't wonder that it works badly. We wonder that it works at all.)
You can get the latest (largest) value of HISTORY_ID for each value of SERIAL_NUMBER from your table like this:
SELECT MAX(HISTORY_ID) FROM history_card GROUP BY SERIAL_NUMBER
Then you can use that set of HISTORY_ID values to retrieve what you want from your table.
SELECT SERIAL_NUMBER, PART_NUMBER, POSITION, DUE_CAP_CHECK_DATE, DUE_OVERHAUL_DATE
FROM history_card
WHERE HISTORY_ID
IN (SELECT MAX(HISTORY_ID) FROM history_card GROUP BY SERIAL_NUMBER)

This slow MySQL Query needs improvement

This query works and provides me with the information I need, but it is very slow: it takes 18 seconds to agregate a database of only 4,000 records.
I'm bringing it here to see if anyone has any advice on how to improve it.
SELECT COUNT( status ) AS quantity, status
FROM log_table
WHERE time_stamp
IN (SELECT MAX( time_stamp ) FROM log_table GROUP BY userid )
GROUP BY status
Here's what it does/what it needs to do in plain text:
I have a table full of logs, each log contains a "userid", "status" (integer between 1-12) and "time_stamp" (a time stamp of when the log was created). There may be many entries for a particular userid, but with a different time stamp and status. I'm trying to get the most recent status (based on time_stamp) for each userid, then count the occurrences of each most-recent status among all the users.
My initial idea was to use a sub query with GROUP BY userid, that worked fast - but that always returned the first entry for each userid, not the most recent. If I could do GROUP BY userid using time_stamp DESC to Identify which row should be the representative for the group, that would be great. But of course ORDER BY inside of group does not work.
Any suggestions?
The first thing to try is to make this an explicit join:
SELECT COUNT(status) AS quantity, status
FROM log_table join
(select lg.userid, MAX( time_stamp ) as maxts
from log_table lg
GROUP BY userid
) lgu
on lgu.userid = lg.userid and lgu.maxts = lg.time_stamp
GROUP BY status;
Another approach is to use a different where clause. This will work best if you have an index on log_table(userid, time_stamp). This approach is doing the filtering by saying "there is no timestamp bigger than this one for a given user":
SELECT COUNT(status) AS quantity, status
FROM log_table
WHERE not exists (select 1
from log_table lg2
where lgu.userid = lg.userid and lg2.time_stamp > lg.time_stamp
)
GROUP BY status;

Aggregate function in BETWEEN and AND

I have joined 3 tables in my query. In my Inventory db,Price is taken from table c and quantity is taken from table b. How can I show the records list of users who have ordered between the given value and maximum value of the column.
I am using below query in mysql to retrieve records. As expected it shows error. Any help will be highly appreciated
SELECT .... GROUP BY userid HAVING SUM(c.`price` * b.`quantity`) BETWEEN 9000 AND MAX(SUM(c.`price` * b.`quantity`))
If I understand correctly you don't need BETWEEN. Try it this way
SELECT ....
GROUP BY userid
HAVING SUM(c.`price` * b.`quantity`) >= 9000
In case you wondered you can't chain aggregate functions. And even if you could it wouldn't make sense because you group by userid, but trying to get MAX of SUM from all users. In order for this to work you should've used a subquery to get max value e.g.
SELECT ....
GROUP BY userid
HAVING SUM(c.`price` * b.`quantity`) =
(
SELECT MAX(total) total
FROM
(
SELECT SUM(c.`price` * b.`quantity`) total
GROUP BY userid
) q
)

Group by user and show latest in MYSQL not working

I have a social network I am coding but it's a bit different than others, in this case there is only ever one status show per user on a feed section.
So I need to sort the status by date with the latest ones on top but also group by the userID
unfortunately I can't seem to get this working....
This is my current query:
SELECT *
FROM status
WHERE userID != "83" #This is just so my statuses don't show
GROUP BY userID
ORDER BY addedDate DESC
LIMIT 10
I expect to see the latest status results and only one per user instead I see the first statuses so the group by is working but not the order by.
Thanks in advance.
As mentioned in the comments to Robin's answer, that approach is unreliable because MySQL does not guarantee that it will always return the most recent status from each group. You must instead join your table with a subquery that selects the most recent status (based on addedDate).
SELECT *
FROM status
NATURAL JOIN (
SELECT userID, MAX(addedDate) as addedDate
FROM status
GROUP BY userID
) AS mostRecent
ORDER BY addedDate DESC
LIMIT 10
Note that if a user has multiple status updates with the same addedDate, the server will return all of them (whereas Robin's query would return an indeterminate one); if you need control over such a situation, you will need to define how one determines which such status update should be selected.
SELECT userID, max(addedDate)
FROM status
WHERE userID != "83" #This is just so my statuses don't show
GROUP BY userID
SELECT *
FROM ( SELECT *
FROM status
WHERE userID != "83"
ORDER BY addedDate DESC) AS h
GROUP BY userID
ORDER BY addedDate DESC
LIMIT 10
You must ORDER BY before GROUP BY'ing.
Example 1
Example 2

Determine total amount of top result returned

I would like to determine two things from a single query:
Most prevalent column in a table
The amount of times such column was located upon querying the table
Example Table:
user_id some_field
1 data
2 data
1 data
The above would return user_id # 1 as being the most prevalent in the table, and it would return (2) for the total amount of times that it was located in the table.
I have done my research and I came across two types of queries.
GROUP BY user_id ORDER BY COUNT(*) DESC
SUM
The problem is that I can't figure out how to use these two queries in conjunction with one another. For example, consider the following query which successfully returns the most prevalent column.
$top_user = "SELECT user_id FROM table_name GROUP BY user_id ORDER BY COUNT(*) DESC";
The above query returns "1" based on the example table shown above. Now, I would like to be able to return "2" for the total amount of times the user_id (1) was found in the table.
Is this by any chance possible?
Thanks,
Evan
You can include count(*) in the SELECT list:
SELECT user_id, count(*) as totaltimes from table_name
GROUP BY user_id ORDER BY count(*) DESC;
If you want only the first one:
SELECT user_id, count(*) as totaltimes from table_name
GROUP BY user_id ORDER BY count(*) DESC LIMIT 1;