Include another select column based on data - MySQL - mysql

How do I include SUM((pm.Quantity * bl.TotalQty)) AS NextBOMItemCount WHERE projectbomlist.ParentPartNum = bl.PartNum?
The data should not be changed, the same data should be retrieved, the however additional column has to be included.
VIEW: `NEWprojectBOMItemCount
select
`pm`.`ProjectCode` AS `ProjectCode`,
`bl`.`PartNum` AS `PartNum`,
sum((`pm`.`Quantity` * `bl`.`TotalQty`)) AS `BOMItemCount`,
`bl`.`mp` AS `mp`,
`p`.`complete` AS `complete`,
`bl`.`RMInd` AS `RMInd`,
`bl`.`M_PartNum` AS `M_PartNum`
from
(
(`projectmachine` `pm` join `projectbomlist` `bl`)
join `projects` `p`
)
where
(
(`pm`.`MachineListID` = `bl`.`MachineListID`)
and (`pm`.`ProjectCode` = `bl`.`ProjectCode`)
and (`pm`.`ProjectCode` = `p`.`ProjectCode`)
and (`p`.`AfterProjectHeirarchyInd` = 'Y')
)
and and pm.ProjectCode = 'AB212323'
group by
`pm`.`ProjectCode` ,
`bl`.`PartNum`
order by
`pm`.`ProjectCode` ,
`bl`.`PartNum`
Or, another option can be, please consider above view used in below query, please suggest changes to the below query as shown above (repeating here)
`sum((pm.Quantity * bl.TotalQty)) AS NextBOMItemCount where projectbomlist.ParentPartNum = bl.PartNum` - in place of `(select-NextBOMItemCount)`?
Please see PBLH.ParentPartNum is the column that I should compare with BL.ProjectCode to get NextBOMItemCount value.
QUERY calling view: NEWprojectBOMItemCount
Select
BL.PartNum PartNumber,
PBLH.ParentPartNum NextBOM,
(select-NextBOMItemCount),
BOMItemCount TotalQty,
PL.Description,
BL.MP as PartType,
PL.Vendor,
PL.QBType
from
NEWprojectBOMItemcount BL,
bomwiz.partslist PL,
bomwiz.projectbomlistheirarchy PBLH
Where
BL.PartNum = PL.PartNum
And BL.PartNum = PBLH.PartNum
And BL.ProjectCode = PBLH.ProjectCode
And BL.projectCode = 'AB212323'
Order By PartNumber

I think that you are looking for conditional aggregation. Your requirement could be expressed as follows:
SUM(
CASE WHEN blh.ParentPartNum = bl.PartNum
THEN pm.Quantity * bl.TotalQty
ELSE 0
END
) AS NextBOMItemCount
Let me pinpoint other issues with your query:
you have unwanted parentheses all around, and I am suspicious about the syntax of the JOINs ; you need to move conditions to the ON clause of the relevant JOIN.
every non-aggregated column must appear in the GROUP BY clause - you have missing columns there
backquotes are usually not needed
Here is an updated version of the query:
SELECT
pm.ProjectCode AS ProjectCode,
bl.PartNum AS PartNum,
SUM(pm.Quantity * bl.TotalQty) AS BOMItemCount,
SUM(
CASE WHEN blh.ParentPartNum = bl.PartNum
THEN pm.Quantity * bl.TotalQty
ELSE 0
END
) AS NextBOMItemCount,
bl.mp AS mp,
p.complete AS complete,
bl.RMInd AS RMInd,
bl.M_PartNum AS M_PartNum
FROM
projectmachine AS pm
INNER JOIN projectbomlist AS bl
ON pm.MachineListID = bl.MachineListID
AND pm.ProjectCode = bl.ProjectCode
INNER JOIN join projects AS p
ON pm.ProjectCode = p.ProjectCode
AND p.AfterProjectHeirarchyInd = 'Y'
INNER JOIN projectbomlistheirarchy blh
ON bl.ProjectCode = blh.ProjectCode
WHERE
pm.ProjectCode = 'AB212323'
GROUP BY
pm.ProjectCode,
bl.PartNum,
bl.mp,
p.complete,
bl.RMInd,
bl.M_PartNum
ORDER BY
pm.ProjectCode,
bl.PartNum

Related

SQL - Divide One Query by Another

I am trying to create a query which returns the workout percentage completion...
Workout Percentage Completion =
((Sum of LogEntries WHERE date = IN list of dates and WorkoutID =1 ) /
(Sum of all set numbers WHERE WorkoutID = 1))
x 100
Below is what I currently have, at the moment it is only returning the result of the first query.
What should I change for the query to run correctly?
SELECT
(
(
SELECT COUNT(LogEntriesID)
FROM LogEntriesTable
LEFT JOIN ExerciseWorkoutJunctionTable
ON ExerciseWorkoutJunctionTable.ExerciseWorkoutJunctionID =
LogEntriesTable.JunctionID
WHERE LogEntriesTable.date IN (
"14-05-2020", "15-05-2020", "16-05-2020", "17-05-2020",
"18-05-2020", "19-05-2020", "20-05-2020"
)
AND ExerciseWorkoutJunctionTable.WorkoutID = 1
) / (
SELECT sum(SetNumber)
FROM ExerciseWorkoutGoalsTable
LEFT JOIN ExerciseWorkoutJunctionTable
ON ExerciseWorkoutJunctionTable.ExerciseWorkoutJunctionID =
ExerciseWorkoutGoalsTable.JunctionID
WHERE ExerciseWorkoutJunctionTable.WorkoutID = 1
)
)
Your first SELECT statement is doing an OUTER JOIN but then you have a WHERE clause that is selecting non-NULL values from the ExerciseWorkoutJunctionTable table, so I suspect you might as well be doing an INNER JOIN.
When you have two queries, try:
SET #sum = (SELECT SUM(SetNumber) etc ....);
SELECT (COUNT(LogEntriesID) * 100 / #sum) AS percentage
FROM etc.
If you are using MySQL >= 8.0 you should be able to use window functions like this which breakdown your query into more readable sections.
with entries as (
SELECT COUNT(LogEntriesID) as log_entry_count
FROM LogEntriesTable as l
LEFT JOIN ExerciseWorkoutJunctionTable as e ON
e.ExerciseWorkoutJunctionID = l.JunctionID
WHERE l.date IN ("14-05-2020","15-05-2020","16-05-2020","17-05-2020","18-05-2020","19-05-2020","20-05-2020")
AND e.WorkoutID = 1
),
sets as (
SELECT sum(SetNumber) as set_sum
FROM ExerciseWorkoutGoalsTable as eg
LEFT JOIN ExerciseWorkoutJunctionTable ej
ON ej.ExerciseWorkoutJunctionID = eg.JunctionID
WHERE ej.WorkoutID = 1
)
select ((select log_entry_count from entries) / (select set_sum from sets)) * 100 as workout_completion_pct

Where clause using alias column with IF and IFNULL

I have an mysql query like below:
SELECT
sppt_ticket.*,
IF(sppt_read_support_ticket.ID_aks_user IS NULL,'N', 'Y') AS `read_status`,
IFNULL(readcomment.total_comment, 0) AS unread_comment
FROM
sppt_ticket
LEFT JOIN
sppt_read_support_ticket ON
sppt_ticket.ID_support_ticket = sppt_read_support_ticket.ID_support_ticket AND
ID_aks_user = 1
LEFT JOIN
(SELECT
sppt_comment.ID_support_ticket, SUM(IF(sppt_read_comment.ID_aks_user IS NULL, 1, 0))
AS
total_comment
FROM
sppt_comment
LEFT JOIN
sppt_read_comment
ON
sppt_comment.ID_comment = sppt_read_comment.ID_comment
AND
sppt_read_comment.ID_aks_user = 1
GROUP BY
sppt_comment.ID_support_ticket) AS readcomment ON readcomment.ID_support_ticket = sppt_ticket.ID_support_ticket
What I want to get in where clause is like this
WHERE read_status = 'Y'
I've tried using subquery, but still I didn't get it..
any help?
Have you tried this:
SELECT * FROM
(
-- your original query as a table
SELECT
sppt_ticket.*,
IF(sppt_read_support_ticket.ID_aks_user IS NULL,'N', 'Y') AS `read_status`,
IFNULL(readcomment.total_comment, 0) AS unread_comment
FROM
sppt_ticket
LEFT JOIN
sppt_read_support_ticket ON
sppt_ticket.ID_support_ticket = sppt_read_support_ticket.ID_support_ticket AND
ID_aks_user = 1
LEFT JOIN
(SELECT
sppt_comment.ID_support_ticket, SUM(IF(sppt_read_comment.ID_aks_user IS NULL, 1, 0))
AS
total_comment
FROM
sppt_comment
LEFT JOIN
sppt_read_comment
ON
sppt_comment.ID_comment = sppt_read_comment.ID_comment
AND
sppt_read_comment.ID_aks_user = 1
GROUP BY
sppt_comment.ID_support_ticket) AS readcomment ON readcomment.ID_support_ticket = sppt_ticket.ID_support_ticket
)
as temptable
where read_status = 'Y' -- this should work
Or you can use HAVING instead of WHERE if you do not want to treat your query as a table:
SELECT
sppt_ticket.*,
IF(sppt_read_support_ticket.ID_aks_user IS NULL,'N', 'Y') AS `read_status`,
IFNULL(readcomment.total_comment, 0) AS unread_comment
FROM
sppt_ticket
LEFT JOIN
sppt_read_support_ticket ON
sppt_ticket.ID_support_ticket = sppt_read_support_ticket.ID_support_ticket AND
ID_aks_user = 1
LEFT JOIN
(SELECT
sppt_comment.ID_support_ticket, SUM(IF(sppt_read_comment.ID_aks_user IS NULL, 1, 0))
AS
total_comment
FROM
sppt_comment
LEFT JOIN
sppt_read_comment
ON
sppt_comment.ID_comment = sppt_read_comment.ID_comment
AND
sppt_read_comment.ID_aks_user = 1
GROUP BY
sppt_comment.ID_support_ticket) AS readcomment ON readcomment.ID_support_ticket = sppt_ticket.ID_support_ticket
HAVING read_status = 'Y' -- use HAVING instead of WHERE
The reason why treating your original query as a table works is because of the way values are evaluated in the query. In your original query, the alias read_status cannot be used with the WHERE clause because the actual value might not yet be known when the WHERE clause is evaluated. As documented in Section B.1.5.4, “Problems with Column Aliases”. Treating it as a table ensures that the value for read_status has already been evaluated.
For the HAVING approach, MySQL created an extension to standard SQL that permits references in the HAVING clause to aliased expressions in the select list.

SQL Subquery return more than 1 row

I need to set "dph" in this table "Strobjednavka", but i don´t know whats wrong there. Please help :).
Here is my SQL script:
UPDATE STRObjednavka as o SET dph = (
SELECT dph FROM STRCena WHERE
menuKodCode =
(SELECT menuKodCode FROM STRMenu WHERE
id = o.menuId
)
AND
skupinaId =
(SELECT stravGroupId FROM grups1 WHERE
PKey =
(SELECT SGroup FROM users1 WHERE
PKey = o.userId
)))
WHERE o.price > 0 AND `date` > '2015-01-28 13:52:36' AND dph = 0;
SQL say : SQL error 1242: Subquery returns more than 1 row
You can able to update with below script, but you need to check whether update is correct or not, If you give some sample data then it will be easy to track the problem.
UPDATE STRObjednavka as o SET dph = (
SELECT max(dph) FROM STRCena WHERE
menuKodCode =
(SELECT max(menuKodCode) FROM STRMenu WHERE
id = o.menuId
)
AND
skupinaId =
(SELECT max(stravGroupId) FROM grups1 WHERE
PKey =
(SELECT max(SGroup) FROM users1 WHERE
PKey = o.userId
)))
WHERE o.price > 0 AND `date` > '2015-01-28 13:52:36' AND dph = 0;
Unfortunately, MySQL doesn't allow you to LIMIT a subquery. Depending on your use case you can add MIN or MAX to your subqueries. Here it is with MINs in all the subqueries:
UPDATE STRObjednavka as o SET dph = (
SELECT MIN(dph) FROM STRCena WHERE
menuKodCode =
(SELECT MIN(menuKodCode) FROM STRMenu WHERE
id = o.menuId
)
AND
skupinaId =
(SELECT MIN(stravGroupId) FROM grups1 WHERE
PKey =
(SELECT MIN(SGroup) FROM users1 WHERE
PKey = o.userId
)))
WHERE o.price > 0 AND `date` > '2015-01-28 13:52:36' AND dph = 0;
Although you really only need to add it to the subquery that's returning more than one row.
Your first problem is that you're writing '.... = (SELECT .... )'. Since you're using the equality operator, you're asking SQL to assign an entire column of values to a single cell. Change your equality operators before your subqueries to IN operators.
You probably should use a different query pattern.
You have this sort of thing in your query, in several places.
WHERE menuKodCode = /* !! might generate error 1242 */
(SELECT menuKodCode FROM STRMenu WHERE id = o.menuId)
There's no guarantee that your inner query won't return more than one row, and when it does, MySQL throws error 1242.
SQL works wiith sets of values. If you used IN instead of =, your query would work.
WHERE ... menuKodCode IN
(SELECT menuKodCode FROM STRMenu WHERE id = o.menuId)
But you should figure out whether that logic is correct. If I were you I'd do a whole bunch of SELECT operations to test it before doing UPDATE.

How to query mysql to select and group by multiple values

I'm trying to select and group by all the contentid values of the table below where the match criteria can be several different values.
the contentid values actually represent cars, so I need to select [and group by] all the contentis where the values are 'GMC' and the values are 'sedan' and the value is 'automatic.
i.e. I'm trying to select all the GMC sedans with an automatic transmission.
a query like this fails [obviously]:
select * from modx_site_tmplvar_contentvalues WHERE
`value` = 'gmc' and
`value` = 'tacoma'
group by contentid
I have no idea how to create a query like that. Any suggestions?
You need to "pivot" these data on "tmplvarid", but unfortunately for you MySQL doesn't have a PIVOT statement like other RDBMS. However, you can pivot it yourself by joining in the table multiple times for each variable you care about:
SELECT
contents.contentid,
transmission.value as transmission,
type.value as type,
make.value as make
FROM
(SELECT DISTINCT contentid FROM modx_site_tmplvar_contentvalues) AS contents
LEFT JOIN
modx_site_tmplvar_contentvalues AS transmission
ON contents.contentid = transmission.contentid
AND transmission.tmplvarid = 33 -- id for transmission
LEFT JOIN
modx_site_tmplvar_contentvalues AS make
ON contents.contentid = make.contentid
AND make.tmplvarid = 13 -- id for make
LEFT JOIN
modx_site_tmplvar_contentvalues AS type
ON contents.contentid = type.contentid
AND type.tmplvarid = 17 -- id for type
WHERE
type.value = 'sedan'
AND make.value = 'GMC'
AND transmission.value = 'automatic'
You can expand this with additional joins for other criteria such as year (id 15) or mileage (id 16).
If you need to use the value only, you could try:
SELECT DISTINCT
contents.contentid,
transmission.value as transmission,
type.value as type,
make.value as make
FROM
(SELECT DISTINCT contentid FROM modx_site_tmplvar_contentvalues) AS contents
INNER JOIN
modx_site_tmplvar_contentvalues AS transmission
ON contents.contentid = transmission.contentid
AND transmission.value = 'automatic'
INNER JOIN
modx_site_tmplvar_contentvalues AS make
ON contents.contentid = make.contentid
AND make.value = 'GMC'
INNER JOIN
modx_site_tmplvar_contentvalues AS type
ON contents.contentid = type.contentid
AND type.value = 'sedan'
In any case, make sure you have an index on the value column; these queries are going to get slow.
please try this:
SELECT *
FROM modx_site_tmplvar_contentvalues t1 INNER JOIN modx_site_tmplvar_contentvalues t2 ON t1.contentid = t2.content_id
WHERE
t1.`value` = 'gmc'
AND t2.`value` = 'tacoma';
You can do this with a group by. This is the most flexible in terms of expressing the conditions. In MySQL, multiple joins will often perform better:
select contentid
from modx_site_tmplvar_contentvalues
group by contentid
having sum(`value` = 'gmc') > 0 and
sum(`value` = 'tacoma') > 0;
This is always false:
`value` = 'gmc' and
`value` = 'tacoma'
Instead, use OR:
`value` = 'gmc' OR
`value` = 'tacoma'
In a condition "and" means "this and this is true at the same time". If you want all foos and all bars, then your condition is "foo OR bar".
EDIT:
To select groups containing your values, you can write subqueries:
SELECT DISTINCT name FROM table WHERE name IN (SELECT name FROM table WHERE value='value1') AND name IN (SELECT name FROM table WHERE value='value2')

MySQL LEFT JOIN Problem - Missing LEFT column

I'm having problems with an SQL query used to display custom profile fields and any (optional) corresponding values.
Here is the SQL query I'm using:
SELECT pf.`id`, pf.`name`, pv.`value` FROM `profile_fields` AS pf
LEFT JOIN `profile_values` AS pv ON (pf.`id` = pv.`field_id`)
WHERE (pf.`site_id` = '0' OR pf.`site_id` = '%d') AND (pv.`user_id` = '%d' OR pv.`user_id` IS NULL)
ORDER BY pf.`order` ASC
The problem I'm having is that any columns with no corresponding profile_values records are not shown at all, when they should show, but just with an empty value.
Many thanks!
Try moving the profile values conditions to the JOIN statement:
SELECT pf.`id`, pf.`name`, pv.`value` FROM `profile_fields` AS pf
LEFT JOIN `profile_values` AS pv ON (
pf.`id` = pv.`field_id` AND
(pv.`user_id` = '%d' OR pv.`user_id` IS NULL)
)
WHERE (pf.`site_id` = '0' OR pf.`site_id` = '%d')
ORDER BY pf.`order` ASC