MySQL Group By not producing expected result - mysql

This is my table structure:
rec_id product_id quantity quantity_in quantity_out balance stock_date status
1 2 342 NULL 17 325 2009-10-23 1
2 2 325 NULL 124 201 2009-10-23 1
3 1 156 NULL 45 111 2009-10-23 1
4 2 201 NULL 200 1 2009-10-23 1
5 2 1 NULL 1 0 2009-10-23 1
6 1 111 NULL 35 76 2009-10-23 1
All I want is the last transaction done for a given product: product_id, quantity, quantity_out and balance from this table.
Example, there are 2 transaction done for product 2 (ids 1 & 2):
final balance for product_id 2 is 0 -> stored in rec_id 5
final balance for product_id 1 is 76 -> stored in rec_id 6
Final result/output should be like this:
recid productid quantity quantityin quantityout balance stock_date status
5 2 1 NULL 1 0 2009-10-23 1
6 1 111 NULL 35 76 2009-10-23 1

You can find the latest record for each product like:
select max(rec_id) as MaxRec
from YourTable
group by product_id
Using a subquery, you can retrieve the latest rows for their product:
select *
from YourTable
where rec_id in (
select max(rec_id) as MaxRec
from YourTable
group by product_id
)

Here's a single query with no subqueries:
SELECT main.*
FROM YourTable main
LEFT JOIN YourTable newer
ON newer.product_id = main.product_id AND newer.rec_id > main.rec_id
WHERE newer.rec_id IS NULL;
You can tweak the field list however you want--make sure you select fields from main, not newer, which should be all null.

Related

SQL query for below data

For input, When quantity value greater then 1, convert in a new row with value 1 for quantity column.
INPUT
ID ProductFK Quantity Price
------------------------------------------------
10 1 2 100
11 2 3 150
12 1 1 120
OUTPUT
ID ProductFK Quantity Price
------------------------------------------------
10 1 1 100
10 1 1 100
11 2 1 150
11 2 1 150
11 2 1 150
12 1 1 120
We can do this using a sequence table trick. Inner join your current table to a sequence on the condition that the quantity be greater than or equal to the sequence value. For example:
SELECT t1.ID, t1.ProductFK, 1 AS Quantity, t1.Price
FROM yourTable t1
INNER JOIN (SELECT 1 AS Quantity UNION ALL SELECT 2 UNION ALL SELECT 3) t2
ON t1.Quantity >= t2.Quantity
ORDER BY t1.ID;
Demo

Mysql SELECT when there are multiple values for the search term

I'm trying to select all user_id's from the following table (excerpt) where product_id '3' is not associated with the user_id at all.
user_id product_id status terms_id
100 3 1 10
100 22 0 0
100 402 0 20
101 22 1 10
101 68 1 0
101 120 1 20
201 22 0 0
201 3 1 10
In this example, only user_id 101 should be selected because it doesn't have product_id 3 at all. Each user_id can have multiple entries.
I've tried the following, but it incorrectly selects all the user_id's
SELECT distinct user_id FROM table WHERE product_id <> 3
How could I accomplish this? The actual table has more than 3.5 million rows.
Thanks!
You can use a NOT EXISTS subquery to check that the user has no associated row with product_id = 3:
SELECT DISTINCT user_id
FROM `table` t1
WHERE NOT EXISTS (SELECT * FROM `table` t2 WHERE t2.user_id = t1.user_id AND t2.product_id = 3)
Output
101
Demo on dbfiddle
An alternate solution is to GROUP BY user_id and to assert that the count of rows with product_id = 3 is 0:
SELECT user_id
FROM `table`
GROUP BY user_id
HAVING SUM(product_id = 3) = 0
Demo on dbfiddle

How to join to single row in one to many relationship in SQL?

I want to join one to many table with single row on many table by limit 1 and order by create date
tbl_cart :
id fullname
1 myname1
2 myname2
3 myname3
tbl_cart_status:
id cart_id status created_at
1 1 33 2018-09-20
2 1 34 2018-09-23
3 2 34 2018-09-21
4 1 100 2018-09-25
5 2 35 2018-09-29
How can i get output with sql like this:
I want to get lastest status of my cart by ordered with created_at column
myname cart_id status created_at
myname1 1 100 2018-09-25
myname2 2 35 2018-09-29
Think filtering for this type of query:
select c.name, cs.*
from tbl_cart c join
tbl_cart_status cs
on c.id = cs.cart_id
where cs.created_at = (select max(cs2.created_at)
from tbl_cart_status cs2
where cs2.cart_id = cs.cart_id
);

count occurence of rows with specific status without using subquery

Here is my table
loan_id bid_id lender_id borrower_id amount interest duration loan_status
1 1 60 63 300.00 12.00 3 'completed'
2 2 61 63 300.00 12.00 3 'completed'
3 3 62 63 300.00 12.00 3 'pending',
4 1 62 63 300.00 12.00 3 'pending'
7 4 60 63 300.00 12.00 3 'completed'
I want to pull only those bid_id whose loan_status of all records is completed. It means if there is any record of bid_id with status pending then it will not pull that record.
I am using the followin query that is working fine:
SELECT bid_id
FROM loan
WHERE bid_id NOT IN (
SELECT l.bid_id
FROM loan l
WHERE l.`loan_status` = 'pending'
AND l.bid_id = bid_id
GROUP BY l.`bid_id`
HAVING COUNT(l.`bid_id`)>= 1
)
GROUP BY bid_id
Is there any other way in which we can get desired result without using sub query.
You can readily do this with group by and having:
select bid_id
from loan
group by bid_id
having sum(loand_status = 'pending') = 0

Increment Group Number based on row value SQL Server 2008

I have two tables that aren't really associated, but need to be combined. So I'm using union all on the two tables. The unioned tables are ordered by date, so rows from one table are dispersed among rows from the other table. What I need to do is get a running count of a column so I can group elements.
To explain further, table A holds dates of when a container is emptied, while table B holds daily entries for content of the container. I need to union the two tables so I have one table where I can get the sum of the information for a container before the container is emptied.
So I need something like this:
Table A:
Location_ID Empty Date
123 3/2/13
123 3/10/13
123 4/1/13
Table B:
PSI Entry Date Location_ID
120 2/28/13 123 (same for all)
130 3/1/13
100 3/8/13
110 3/9/13
200 3/18/13
180 3/20/13
So the unioned table after some magic would look like:
Table C...:
Location_ID Date PSI Emptied
123 2/28/13 120 0
123 3/1/13 130 0
123 3/2/13 null 1
123 3/8/13 100 0
123 3/9/13 110 0
123 3/10/13 null 1
123 3/18/13 200 0
123 3/20/13 180 0
123 4/1/13 null 1
What I need to do is have a grouping such that I can have a table like this
Table C_b
Location_ID Date PSI Emptied Group
123 2/28/13 120 0 1
123 3/1/13 130 0 1
123 3/2/13 null 1 1
123 3/8/13 100 0 2
123 3/9/13 110 0 2
123 3/10/13 null 1 2
123 3/18/13 200 0 3
123 3/20/13 180 0 3
123 4/1/13 null 1 3
How can I get that grouping in that way? I have to make it work in SQL Server 2008. I have tried using Count, and Rank, and Row_Number. But the problem with those is that it won't do a running count, it will just say the total count in each row.
Try this query:
DECLARE #MyTable TABLE(
EntryDate DATE NOT NULL,
Emptied BIT NOT NULL
);
INSERT INTO #MyTable (EntryDate,Emptied)
VALUES
('2013-01-01',0),
('2013-01-02',0),
('2013-01-03',1),
('2013-01-04',0),
('2013-01-05',0),
('2013-01-06',1),
('2013-01-07',0),
('2013-01-08',0),
('2013-01-09',1);
DECLARE #TableWithRowNum TABLE(
EntryDate DATE NOT NULL,
Emptied BIT NOT NULL,
RowNum INT PRIMARY KEY
);
INSERT INTO #TableWithRowNum (EntryDate,Emptied,RowNum)
SELECT crt.*,ROW_NUMBER() OVER(ORDER BY crt.EntryDate) AS RowNum
FROM #MyTable crt;
WITH RecCTE
AS(
SELECT
crt.EntryDate,
crt.Emptied,
crt.RowNum,
1 AS Grp
FROM #TableWithRowNum crt
WHERE crt.RowNum=1
UNION ALL
SELECT
crt.EntryDate,
crt.Emptied,
crt.RowNum,
CASE WHEN prev.Emptied=1 THEN prev.Grp+1 ELSE prev.Grp END
FROM #TableWithRowNum crt INNER JOIN RecCTE prev ON crt.RowNum=prev.RowNum+1
)
SELECT * FROM RecCTE
OPTION(MAXRECURSION 0); -- Default value for MAXRECURSION is 100
GO
Results:
EntryDate Emptied RowNum Grp
---------- ------- ------ ---
2013-01-01 0 1 1
2013-01-02 0 2 1
2013-01-03 1 3 1
2013-01-04 0 4 2
2013-01-05 0 5 2
2013-01-06 1 6 2
2013-01-07 0 7 3
2013-01-08 0 8 3
2013-01-09 1 9 3