Group by a field inside a nested query - mysql

We have a nested sql query we want to group by a field that is into a nested query rather than grouping by a field that is on the main query .
SELECT dataissue.value as a,
COUNT(value),
substring(issue.entry, 1, 3)
FROM DataIssue, issue
WHERE field = 'point_d_effort'
AND dataissue.issue = issue.id
AND issue IN (
SELECT issue
FROM dataissue, issue
WHERE dataissue.issue = issue.id
AND value = 'récit'
AND substring(issue.entry,1,3) = 'ema'
)
AND issue IN (
SELECT issue
FROM dataissue, issue
WHERE dataissue.issue = issue.id
AND value = 'Fermée'
AND substring(issue.entry,1,3) = 'ema'
)
AND issue IN (
SELECT issue
FROM dataissue, issue
WHERE dataissue.issue = issue.id
AND field = 'version(s)_corrigée(s)' AS b
AND substring(issue.entry,1,3) = 'ema'
)
GROUP BY dataissue.value as b
To sumarize: The group by uses the field value alias a inside the main query WHERE field = 'point_d_effort'. However, I want to group by the field ( value alias b ) inside the nested query WHERE field = 'Version(s)_corrigée(s)'.
How may I do that? Thank you.
For more precisions ,
Hi all first of all , i want to thank you for contributing to the answer here is an SQL fiddle
http://sqlfiddle.com/#!9/610e7/1
-- This query will return all the attributes of an issue
select * from dataissue where issue = '25998' .
What I want to have is :
sum(value) count(value)
where field = 'version(s)_corrigée(s)'
and value = 'Fermée'
and field = 'point_d_effort'
and value = 'récit'
and group it by value where field = 'version(s)_corrigée(s)'

SELECT main2.value AS VALUE,nbreticket,ticket FROM
(
SELECT dataissue.issue,dataissue.value,COUNT(VALUE) AS nbreticket,SUM(VALUE) AS ticket,SUBSTRING(issue.entry,1,3) ,FIELD
FROM DataIssue,issue WHERE dataissue.issue = issue.id AND VALUE IS NOT NULL AND FIELD = 'point_d_effort' AND issue IN ( SELECT issue
FROM dataissue,issue WHERE dataissue.issue = issue.id AND VALUE = 'récit'
AND SUBSTRING(issue.entry,1,3) = 'ema' ) AND issue IN ( SELECT issue
FROM dataissue,issue WHERE dataissue.issue = issue.id AND VALUE = 'Fermée'
AND SUBSTRING(issue.entry,1,3) = 'ema' ) AND issue IN ( SELECT issue
FROM dataissue,issue WHERE dataissue.issue = issue.id
AND FIELD = 'version(s)_corrigée(s)' AND SUBSTRING(issue.entry,1,3) = 'ema' )
GROUP BY dataissue.value, issue
) main1 JOIN
(
SELECT issue, `value` FROM DataIssue WHERE
FIELD = 'version(s)_corrigée(s)'
)main2
WHERE main1.issue = main2.issue
GROUP BY main2.value
In your sql GROUP BY clause has alias name, we can't do alias name for group clause.
Again in where condition has alias name, we can't do alias name for where clause also.
In your sql some syntax error is there. I cleared all errors now sql is running fine.
Thank you.

Related

How to use 'Mysql JOIN' with sql text of same table

I want to use mysql's "JOIN"
I want to group rows by "date_text" where "tokenIdx" is "1001" and "datetime_unix" is the highest value.
Is my code wrong?
SELECT `A.idx`
FROM `data_candle_h1` 'A'
JOIN
(
SELECT `date_text`, MAX(`datetime_unix`) AS 'datetime_unix'
FROM `data_candle_h1`
WHERE `tokenIdx` = '1002'
GROUP BY `date_text`
) 'B'
ON `A.datetime_unix` = `B.datetime_unix`
WHERE `A.tokenIdx` = '1002'
Your query is syntactically perfect. Just remove single quotes('') around table aliases (A and B). I have corrected it. Please check this out.
SELECT `A.idx`
FROM `data_candle_h1` A
JOIN
(
SELECT `date_text`, MAX(`datetime_unix`) AS 'datetime_unix'
FROM `data_candle_h1`
WHERE `tokenIdx` = '1002'
GROUP BY `date_text`
) B
ON `A.datetime_unix` = `B.datetime_unix`
WHERE `A.tokenIdx` = '1002'

Include another select column based on data - 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

SQL query to select a value based on certain criteria

I have the following data in my Database:
Id MachineName CategoryName CounterName InstanceName RawValue
11180 SERVER64 Process ID Process w3wp#2 2068
11180 SERVER64 Process Working Set w3wp#2 9310208
Now I want to achieve that if I find the value '2068' for the "ID Process" Countername then I want to retrieve the Working Set RawValue. So based on the value of ID Process I now the [InstanceName] = w3wp#2 and therefore I want the value to retrieve = 9310208
Now I tried different SQL queries:
SELECT *
FROM [dbo].[LoadTest]
WHERE [LoadTestRunId] = '11180' and [CategoryName] = 'Process' and [InstanceName] like 'w3wp%'
But I need a filter. Can anyone guide me into the right direction?
This here will help you. I used variable because you need to find a specific ID
SQL Code
declare #myt table (id int,MachineName nvarchar(50),CategoryName nvarchar(50),CounterName nvarchar(50),InstanceName nvarchar(50),RawValue int)
insert into #myt
values
(11180 ,'SERVER64','Process','ID Process','w3wp#2',2068),
(11180 ,'SERVER64','Process','Working Set','w3wp#2',9310208)
declare #FindID int
Set #FindID = 2068;
with IdProcess as (
Select * from #myt
where RawValue = #FindID and CounterName = 'ID Process'
)
Select a.ID,a.MachineName,a.CategoryName,b.CounterName,a.InstanceName,b.RawValue from IdProcess a
inner join #myt b on a.InstanceName = b.InstanceName and b.CounterName='Working Set'
SQL Code without variable based on ID and InstanceName
with IdProcess as (
Select * from #myt
where CounterName = 'ID Process'
)
Select a.ID,a.MachineName,a.CategoryName,b.CounterName,a.InstanceName,b.RawValue from IdProcess a
inner join #myt b on a.id = b.id and a.InstanceName = b.InstanceName and b.CounterName='Working Set'
SQL Code with CategoryName filter
with IdProcess as (
Select * from #myt
where CounterName = 'ID Process' and CategoryName = 'Process'
)
Select a.ID,a.MachineName,a.CategoryName,b.CounterName,a.InstanceName,b.RawValue from IdProcess a
inner join #myt b on a.id = b.id and a.InstanceName = b.InstanceName and b.CounterName='Working Set'
where b.CategoryName = 'Process'
Result
This will execute.
Select * from (SELECT ROW_NUMBER() OVER(PARTITION BY LoadTestRunId ORDER BY LoadTestRunId DESC) as row,*
FROM [dbo].[LoadTest]) t1 where row=1
with your where clause
Select * from (SELECT ROW_NUMBER() OVER(PARTITION BY LoadTestRunId ORDER BY LoadTestRunId DESC),*
FROM [dbo].[LoadTest]) t1 where t1=1
and [LoadTestRunId] = '11180' and [CategoryName] = 'Process' and [InstanceName] like 'w3wp%'

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.

Assign a value to a field on SELECT statement

im not sure if im doing well with this field calendar.type_event = NULL. Now works well to me because I need to differentiate the second SELECT as a third type.
I want to do something like calendar.type_event = 'shared_event' to differentiate it. But returns a 0, with NULL returns nothing. This is not the problem only I need to know if I can assign my own value: 'shared_event'.
Thanks a lot
The entire query is:
(SELECT
id, type_event
FROM calendar
WHERE user_id = '.$user_id.'
)
UNION
(SELECT
calendar.id, calendar.type_event = NULL
FROM calendar
RIGHT JOIN avisos ON avisos.app_id = calendar.id
WHERE avisos.user_destiny_id = '.$user_id.'
)
ORDER BY fecha_evento ASC
I need to know if I can assign my own value: 'shared_event'.
Yes, you can. In place of column calendar.type_event just use literal 'shared_event'
Example:
SELECT
calendar.id, 'shared_event'
FROM calendar
RIGHT JOIN avisos ON avisos.app_id = calendar.id
WHERE avisos.user_destiny_id = '.$user_id.'
You should be able to do something like this:
(SELECT
id, type_event
FROM calendar
WHERE user_id = '.$user_id.'
)
UNION
(SELECT
calendar.id, "shared_event"
FROM calendar
RIGHT JOIN avisos ON avisos.app_id = calendar.id
WHERE avisos.user_destiny_id = '.$user_id.'
)
ORDER BY fecha_evento ASC
I think this is what you are looking for:
(SELECT
id, type_event
FROM calendar
WHERE user_id = '.$user_id.'
)
UNION
(SELECT
calendar.id, '' type_event
FROM calendar
RIGHT JOIN avisos ON avisos.app_id = calendar.id
WHERE avisos.user_destiny_id = '.$user_id.'
)
ORDER BY fecha_evento ASC
In the second query, type_event field will contain null values. If the type_event field is a numeric field, you can put 0 (ZERO) instead of '' (empty single quotes/string).