Query displays different data each time I run it in Mysql - mysql

I have the following query:
SELECT pr_production_units_details.id AS idProductionUnit,
pr_production_units_details.production_units_detail AS productionUnit,
IF(pr_varieties.variety IS NULL, 'SIN SEMBRAR O ERR', pr_varieties.variety)
AS variety
FROM pr_production_units_details
LEFT JOIN
(SELECT MAX(sw_sowing.id) AS ids, sw_sowing.id_production_unit_detail,
sw_sowing.id_variety
FROM sw_sowing
WHERE sw_sowing.status != 0
AND sw_sowing.id_tenant = 1
AND YEARWEEK(sw_sowing.date) <= 201741
GROUP BY sw_sowing.id_production_unit_detail, id_variety
ORDER BY ids DESC
) AS sw
ON pr_production_units_details.id = sw.id_production_unit_detail
INNER JOIN pr_varieties ON sw.id_variety = pr_varieties.id
WHERE pr_production_units_details.id_grouper_detail = 1
AND pr_production_units_details.status = 100
AND pr_production_units_details.id_tenant = 1
GROUP BY pr_production_units_details.id
which brings me the following result:
------------------------------------------------
idProductionUnit | productionUnit | variety
------------------------------------------------
1 | 1 | YELLOW
------------------------------------------------
2 | 2 | YELLOW
------------------------------------------------
3 | 3 | YELLOW
------------------------------------------------
The above result is fine, but every time I run the query, the variety column changes its values, that is:
------------------------------------------------
idProductionUnit | productionUnit | variety
------------------------------------------------
1 | 1 | YELLOW
------------------------------------------------
2 | 2 | BLUE
------------------------------------------------
3 | 3 | YELLOW
------------------------------------------------
also it gives me the following result:
------------------------------------------------
idProductionUnit | productionUnit | variety
------------------------------------------------
1 | 1 | BLUE
------------------------------------------------
2 | 2 | YELLOW
------------------------------------------------
3 | 3 | YELLOW
------------------------------------------------
I do not know if it has to be seen by the ORDER BY or the GROUP BY but I have not understood because it shows me different data.
I hope that you can help me!
Thanks!

I can solve my problem, I change the query like this:
SELECT pr_production_units_details.id AS idProductionUnit, pr_production_units_details.production_units_detail AS productionUnit, pr_varieties.variety
FROM (SELECT MAX(sw_sowing.id) AS id
FROM sw_sowing
WHERE sw_sowing.status != 0
AND sw_sowing.id_tenant = 1
AND YEARWEEK(sw_sowing.date) <= 201741
GROUP BY sw_sowing.id_production_unit_detail
)AS sw
INNER JOIN sw_sowing ON sw_sowing.id = sw.id
INNER JOIN pr_production_units_details ON pr_production_units_details.id = sw_sowing.id_production_unit_detail
INNER JOIN pr_varieties ON pr_varieties.id = sw_sowing.id_variety
WHERE sw_sowing.status != 0
AND sw_sowing.id_tenant =1
AND pr_production_units_details.id_grouper_detail = 13
GROUP BY pr_production_units_details.id, variety
I follow the instructions about the comments and my error only shows me depending the Mysql versions
Thanks for the help!

Related

Laravel Selection Query with left join

Table - tbl_user_details
UserId | Username
------------------
1 | jijo
2 | libin
Table - tbl_user_followups
FollowupId | UserId | Status
---------------------------------
1 | 1 | Negative
2 | 1 | Neutral
3 | 1 | Positive
My Controller is
$result= DB::table('tbl_user_details')
->leftjoin('tbl_user_followups','tbl_user_details.UserId','=','tbl_user_followups.UserId')
->select('tbl_user_details.*','tbl_user_followups.*')
->orderBy('tbl_user_followups.FollowupId','DESC')
->groupBy('tbl_user_details.UserId')
->get();
I want to get the output like as below
UserId | Username | FollowupId | Status
----------------------------------------
1 | jijo | 3 | Positive
2 | libin
Anyone can you please suggest an edit in my controller ???
Not sure if I understood question right: You want list of users with last "followup"? If it is so, then:
SELECT d.userid,
d.username,
det.followupid,
det.status
FROM tbl_user_details d
LEFT JOIN (SELECT userid,
followupid,
status
FROM tbl_user_followups f
WHERE followupid IN (SELECT Max(followupid)
FROM tbl_user_followups
GROUP BY userid)) det
ON d.userid = det.userid
ORDER BY det.followupid DESC;
order by det.followupid desc;
Please note that "order by det.followupid" will not sort them correctly, as we expect for some users to have "null" followupid.

Ordering issue when using SQL variable

I run this query:
SELECT stockcarddetail.id, stockcarddetail.date, stockcarddetail.quantity, stockcarddetail.pricePerItem
FROM Stockcard
LEFT JOIN staff
ON staff.branchId = stockcard.branchId
LEFT JOIN stockcarddetail
ON stockcarddetail.stockcardId = stockcard.id
WHERE staff.username = 'jemmy.h'
AND stockcarddetail.quantity > 0
AND stockcard.productId = '98924a5f-6afb-11e7-8dd4-2c56dcbcb038'
ORDER BY date ASC
and get the result below:
id | date | quantity| pricePerItem
50 | 2017-10-15 | 10.00 | 10000.00
1 | 2017-10-18 | 20.00 | 10000.00
Then, I need to calculate the cumulative of quantity based on the order above, so I run this query:
SELECT a.*, #tot:=#tot + a.quantity FROM
(SELECT #tot:= 0)b
JOIN
(SELECT stockcarddetail.id, stockcarddetail.date, stockcarddetail.quantity, stockcarddetail.pricePerItem
FROM Stockcard
LEFT JOIN staff
ON staff.branchId = stockcard.branchId
LEFT JOIN stockcarddetail
ON stockcarddetail.stockcardId = stockcard.id
WHERE staff.username = 'jemmy.h'
AND stockcarddetail.quantity > 0
AND stockcard.productId = '98924a5f-6afb-11e7-8dd4-2c56dcbcb038'
ORDER BY date ASC) a
Then I got this result:
id | date | quantity| pricePerItem | #tot
1 | 2017-10-18 | 20.00 | 10000.00 | 20
50 | 2017-10-15 | 10.00 | 10000.00 | 30
However, the result that I want is like this:
id | date | quantity| pricePerItem | #tot
50 | 2017-10-15 | 10.00 | 10000.00 | 10
1 | 2017-10-18 | 20.00 | 10000.00 | 30
How can I get the expected result?
EDIT
Simplified version of the problem can be found here: http://sqlfiddle.com/#!9/f6ad91/3
From what I understand from you, you want the cumulative total for each entry.
I suggest ditching the variable and relying on a subquery instead:
SELECT
scd.id,
scd.date,
scd.quantity,
scd.pricePerItem,
(SELECT SUM(scd1.quantity) FROM StockcardDetail AS scd1 WHERE scd1.stockcardId = scd.stockcardId AND scd1.date <= scd.date) AS total
FROM Stockcard
LEFT JOIN staff ON staff.branchId = stockcard.branchId
LEFT JOIN stockcarddetail AS scd ON scd.stockcardId = stockcard.id
WHERE staff.username = 'jemmy.h'
AND scd.quantity > 0
AND stockcard.productId = '98924a5f-6afb-11e7-8dd4-2c56dcbcb038'
ORDER BY scd.date ASC
The idea behind this is to make it select the sum of all entries prior (including the current one) for each entry.
As per my understanding, you should get the expected output from your query. But, you aren't getting your expected output, then other possible solution is (WITHOUT JOIN)
SET #tot:= 0;
SELECT
stockcarddetail.id,
stockcarddetail.date,
stockcarddetail.quantity,
stockcarddetail.pricePerItem,
#tot:=#tot + stockcarddetail.quantity as Total
FROM Stockcard
LEFT JOIN staff ON staff.branchId = stockcard.branchId
LEFT JOIN stockcarddetail ON stockcarddetail.stockcardId = stockcard.id
WHERE staff.username = 'jemmy.h' AND stockcarddetail.quantity > 0 AND stockcard.productId = '98924a5f-6afb-11e7-8dd4-2c56dcbcb038'
ORDER BY date ASC

Count (Select * Join) mysql query

I'm stuck on this for hours, I'm trying to COUNT how many subscribers are there in Group A, Group B, Group C for this particular query:
SELECT rh.id_subscriber, rh.bill_month, rh.bill_year,
(
SELECT tbl_gen_info.gen_data_03
FROM tbl_subscriber
LEFT JOIN tbl_gen_info ON tbl_subscriber.bill_area_code = tbl_gen_info.gen_data_01
WHERE rh.id_subscriber = tbl_subscriber.id_subscriber
) AS group_area
FROM tbl_reading_head AS rh
WHERE rh.id_soa_head IS NULL
AND rh.read_status <> 'Beginning'
AND rh.rec_status = 'active'
ORDER BY rh.id_subscriber
The sub-query gets the Group area gen_data_03 from tbl_gen_info
Tables contain this information:
tbl_gen_info
--------------------------------------------
| gen_category | gen_data_01 | gen_data_03 |
--------------------------------------------
| Area Code | Camacho St. | Group A |
--------------------------------------------
tbl_subscriber
----------------------------------
| id_subscriber | bill_area_code |
----------------------------------
| 1 | Camacho St. |
----------------------------------
tbl_reading_head
----------------------------------------------------------------------
| id_subscriber | id_soa_head | read_status | bill_month | bill_year |
----------------------------------------------------------------------
| 1 | NULL | Metered | 10 | 2017 |
----------------------------------------------------------------------
Notice that each id_subscriber has two (2) rows (one for electric, one for water). After grouping by id_subscriber:
GROUP BY rh.id_subscriber
I got this:
I tried adding COUNT before the sub-query making it:
COUNT(SELECT tbl_gen_info.gen_data_03 ...) AS group_area
but that doesn't work.
Use a subquery:
SELECT rh.group_area, COUNT(*)
FROM (SELECT rh.id_subscriber, rh.bill_month, rh.bill_year,
(SELECT tbl_gen_info.gen_data_03
FROM tbl_subscriber LEFT JOIN
tbl_gen_info
ON tbl_subscriber.bill_area_code = tbl_gen_info.gen_data_01
WHERE rh.id_subscriber = tbl_subscriber.id_subscriber
) as group_area
FROM tbl_reading_head rh
WHERE rh.id_soa_head IS NULL AND
rh.read_status <> 'Beginning' AND
rh.rec_status = 'active'
) rh
GROUP BY rh.group_area;

Selecting row with minimal value in one column, in a join query

I have two tables: tblBusinesses, tblBusinessImages that are matched on tblBusinesses.fldID = tblBusinessImages.fldBusinessID like this:
tblBusinesses
=============
fldID | fldName | fldTitle | fldBody
-------------------------------------
1 | b1 | title1 | body1
2 | b2 | title2 | body2
3 | b3 | title3 | body3
4 | b4 | title4 | body4
tblBusinessImages
=============
fldID | fldFileName | fldTitle | fldBusinessID | fldOrder
-----------------------------------------------------------
1 | img1.jpg | img1title | 1 | 3
2 | img2.jpg | img2title | 1 | 1
3 | img3.jpg | img3title | 1 | 2
I want to write a query that gets for every business in tblBusinesses, the image in tblBusinessImages with minimal fldOrder. In other words, in the example I wrote above I want to get business b1, title1, body1 along with img2.jpg from tblBusinessImages (because it has minimal fldOrder in tblBusinessImages ).
Any help would be appreciated!
If fldOrder alwyas starts at one for each fldBusinessID the query becomes
SELECT b.fldName, b.fldTitle, b.fldBody, i.fldFileName
FROM
tblBusinesses b
LEFT JOIN tblBusinessImages i
ON (b.fldID = i.fldBusinessID AND i.fldOrder = 1)
If not, you will have to use subqueries.
SELECT b.fldName, b.fldTitle, b.fldBody, firstImage.fldFileName
FROM
tblBusinesses b
LEFT JOIN (
SELECT i.fldBusinessID, i.fldFileName
FROM
tblBusinessImages i
WHERE
i.fldOrder = (SELECT MIN(x.fldOrder)
FROM tblBusinessImages x
WHERE x.fldBusinessID = i.fldBusinessID)
) firstImage
ON b.fldID = firstImage.fldBusinessID
Note that the left join makes the query return also businesses having no image at all.
If you need only entries having images where the smallest order id can have any value:
SELECT b.fldName, b.fldTitle, b.fldBody, i.fldFileName
FROM
tblBusinesses b
INNER JOIN tblBusinessImages i
ON b.fldID = i.fldBusinessID
WHERE
i.fldOrder = (SELECT MIN(x.fldOrder)
FROM tblBusinessImages x
WHERE x.fldBusinessID = i.fldBusinessID)
Do you only want to get the ONE entry with the smallest fldOrder?
Didn't test this query:
SELECT b.fldName,b.fldTitle,b.fldBody,bi.fldFileName,bi.fldOrder
FROM tblBuisnesses b
INNER JOIN tblBuisnessImages bi ON bi.fldBusinessID=b.fldID ORDER BY b.fldOrder DESC LIMIT 1;

i am not able to get data from three table geting error #1111 invalid use of group function

i have three tables
table A
------------------------------------------
filing_no | pet_name | res_name | court_no
------------------------------------------
1 | xyz | PQR | 1
------------------------------------------
2 | abc | def | 2
------------------------------------------
Table B
-------------------------------
filing_no |purpose_code|next_date
-----------------------------------
2 | 20 |3/8/2012
-----------------------------------
1 | 21 |3/9/2012
-----------------------------------
2 | 22 |3/10/2012
-----------------------------------
1 | 23 |15/11/2012
-----------------------------------
Table C.
-------------------------------------
purpose_code | purpose_name
-------------------------------------
20 | institution
-------------------------------------
21 | summon
-------------------------------------
22 | proceeding
-------------------------------------
23 | order
-------------------------------------
and i want result of particular court like:
--------------------------------------------------------
filing_no| Pet_name | res_name |purpose_name| next_date
--------------------------------------------------------
1 | xyz | PQR | Order | 15/11/2012
i execute the below query and got #1111 - Invalid use of group function ERROR.
please help.
select
a.filing_no as "File No", a.case_no as "Registration No", a.pet_name as Petitioner, a.res_name as Accused,
a.dt_of_filing as "Date of Inst",MAX(b.Next_date) as "Next Date",c.purpose_name as "Case Stage"
from filing_t a, Daily_proc b, Purpose_t c
where
a.filing_no = b.filing_no
and c.purpose_code = (
select purpose_code
from Daily_proc
where
filing_no = a.filing_no
and next_date = (
select MAX(next_date)
from Daily_proc
where filing_no = a.filing_no
)
)
and a.court_no = 1
and a.ci_cri = 2
and a.status = 'P'
group by b.filing_no
order by a.dt_of_filing DESC LIMIT 0 , 2000
You can only select the columns in GROUP BY and results from aggregate functions. For example what a.pet_name do you expect to be returned when there are different ones for the same b.filling_no?
answer Shared by #Devart i am very thankfull to him.
SELECT a.filing_no, a.pet_name, a.res_name, c.purpose_name, b.next_date FROM a
JOIN (SELECT * FROM (
SELECT * FROM b ORDER BY filing_no, next_date DESC
) t GROUP BY filing_no) b
ON a.filing_no = b.filing_no
JOIN c
ON b.purpose_code = c.purpose_code
WHERE a.court_no = 1;