Why do I can't execute my string? - mysql

I create a string dynamically to perform this by EXECUTE. It throws an exception - why?
As you see I return my string before I try to execute it. When I run this result in a MySQL client instead of CALL procedure () it works flawlessly.
If I try to return my PREPAREd string I get no result. It seems PREPARE kinda breaks my string.
The exception
Error Code: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT movie_name, #ClearLOGOs:=IF((SELECT COUNT(image_id) FROM movie_images WHE' at line 1
The most important sql
SET set_part = CONCAT(set_part, '; ');
SET having_part = CONCAT(having_part, ' ORDER BY completeness ASC');
SET completeness_part = CONCAT(completeness_part, ') AS completeness');
SET complete_select = CONCAT('',set_part, select_part, completeness_part, ' FROM movie_items ',having_part);
SET #exec = complete_select;
SELECT #exec;
PREPARE _exec FROM #exec;
EXECUTE _exec;
The result (unformatted, exact copy)
SET #ClearLOGOs=0, #ClearART=0, #cdART=0, #Movie_Backgrounds=0, #Movie_Banner=0, #HD_Movie_Logos=0, #Movie_Thumbs=0, #HD_ClearART=0, #Movie_Poster=0; SELECT movie_name, #ClearLOGOs:=IF((SELECT COUNT(image_id) FROM movie_images WHERE image_active = 'y' AND image_type = '10' AND image_movie_tmdb_id = movie_tmdb_id) > 0, 0, 1) AS ClearLOGOs, #ClearART:=IF((SELECT COUNT(image_id) FROM movie_images WHERE image_active = 'y' AND image_type = '11' AND image_movie_tmdb_id = movie_tmdb_id) > 0, 0, 1) AS ClearART, #cdART:=IF((SELECT COUNT(image_id) FROM movie_images WHERE image_active = 'y' AND image_type = '12' AND image_movie_tmdb_id = movie_tmdb_id) > 0, 0, 1) AS cdART, #Movie_Backgrounds:=IF((SELECT COUNT(image_id) FROM movie_images WHERE image_active = 'y' AND image_type = '16' AND image_movie_tmdb_id = movie_tmdb_id) > 0, 0, 1) AS Movie_Backgrounds, #Movie_Banner:=IF((SELECT COUNT(image_id) FROM movie_images WHERE image_active = 'y' AND image_type = '19' AND image_movie_tmdb_id = movie_tmdb_id) > 0, 0, 1) AS Movie_Banner, #HD_Movie_Logos:=IF((SELECT COUNT(image_id) FROM movie_images WHERE image_active = 'y' AND image_type = '23' AND image_movie_tmdb_id = movie_tmdb_id) > 0, 0, 1) AS HD_Movie_Logos, #Movie_Thumbs:=IF((SELECT COUNT(image_id) FROM movie_images WHERE image_active = 'y' AND image_type = '24' AND image_movie_tmdb_id = movie_tmdb_id) > 0, 0, 1) AS Movie_Thumbs, #HD_ClearART:=IF((SELECT COUNT(image_id) FROM movie_images WHERE image_active = 'y' AND image_type = '26' AND image_movie_tmdb_id = movie_tmdb_id) > 0, 0, 1) AS HD_ClearART, #Movie_Poster:=IF((SELECT COUNT(image_id) FROM movie_images WHERE image_active = 'y' AND image_type = '29' AND image_movie_tmdb_id = movie_tmdb_id) > 0, 0, 1) AS Movie_Poster,(#ClearLOGOs + #ClearART + #cdART + #Movie_Backgrounds + #Movie_Banner + #HD_Movie_Logos + #Movie_Thumbs + #HD_ClearART + #Movie_Poster) AS completeness FROM movie_items HAVING ClearLOGOs > 0 OR ClearART > 0 OR cdART > 0 OR Movie_Backgrounds > 0 OR Movie_Banner > 0 OR HD_Movie_Logos > 0 OR Movie_Thumbs > 0 OR HD_ClearART > 0 OR Movie_Poster > 0 ORDER BY completeness ASC

You can't use more than one query within prepared statements.
SQL syntax for prepared statements does not support multi-statements (that is, multiple statements within a single string separated by “;” characters).
http://dev.mysql.com/doc/refman/5.0/en/sql-syntax-prepared-statements.html

Related

Left outer join MYSQL returning duplicate rows

I have this MYSQL Query:
select
sc.supplier,
sq.query_value,
sc.cnv_name as name,
sc.cnv_id,
sq.query_type_id,
qt.query_type_desc,
date_format(sq.query_date, '%d/%m/%Y') as query_date,
qs.query_status,
sq.sla_count,
sq.sla_state,
sq.assigned_to,
IfNull(teams.team_count, 0) team_count,
if(
sq.sla_state is null
OR sq.sla_state = '',
'',
if(
sq.sla_state = 0,
'Query Handler',
if(
sq.sla_state = 1,
'Team Leader',
if(
sq.sla_state = 2,
'Manager',
if(
sq.sla_state = 3,
'Senior Manager',
'Senior Manager (GSCOP BREACH)'
)
)
)
)
) as sla_state_desc,
if(
team_count <= 0
OR team_count is null,
'',
if(team_count > 1, '(multiple)', pt.team_desc)
) as team
from
supconversation sc
left outer join supconvers_querydtls sq on sq.cnv_id = sc.cnv_id
left outer join querytype qt on qt.query_type_id = sq.query_type_id
left outer join querystatus qs on qs.query_status_id = sq.query_status_id
left outer join (
select
count(*) team_count,
tu.user_id
from
teamusers tu,
supconvers_querydtls sq2
where
tu.user_id = sq2.assigned_to
) teams on (teams.user_id = sq.assigned_to)
left outer join teamusers tu on tu.user_id = sq.assigned_to
left outer join portalteam pt on pt.team_id = tu.team_id
where
sc.supplier = 'SUPTEST1'
and sc.cnv_type = 'Q'
order by
query_date desc
What I am trying to do is check if a user has a record in teamusers. The user can be a part of more than 1 team. This is stored in the teamusers table with the columns team_id, user_id. If a user has more than 1 record in teamusers then return team value as (multiple). Otherwise, return the team_desc found in the portalteam table. The portalteam table consists of the columns team_id,team_desc.
This query seems to work but it's returning duplicate rows. I imagine this is because there are multiple records for some users in teamusers. How would I go about fixing this issue?
If you really get duplicated rows then you could try using a select DISTINCT
select distinct
sc.supplier,
sq.query_value,
sc.cnv_name as name,
sc.cnv_id,
sq.query_type_id,
qt.query_type_desc,
date_format(sq.query_date, '%d/%m/%Y') as query_date,
qs.query_status,
sq.sla_count,
sq.sla_state,
sq.assigned_to,
IfNull(teams.team_count, 0) team_count,
if(
sq.sla_state is null
OR sq.sla_state = '',
'',
if(
sq.sla_state = 0,
'Query Handler',
if(
sq.sla_state = 1,
'Team Leader',
if(
sq.sla_state = 2,
'Manager',
if(
sq.sla_state = 3,
'Senior Manager',
'Senior Manager (GSCOP BREACH)'
)
)
)
)
) as sla_state_desc,
if(
team_count <= 0
OR team_count is null,
'',
if(team_count > 1, '(multiple)', pt.team_desc)
) as team
from
supconversation sc
.....
.....

MySQL getting and Invalid use of group function

I'm trying to count the result of tc.personnel_id if there's more than 1 result, then the output is 1. And then finally, it will get the sum. But I am getting an "Invalid use of group function" error when i execute this code. Any help will be appreciated.
SELECT tv.id,
tv.vesselName,
SUM(IF(tpi.returningCrew = 0, 1,
IF(
COUNT(tc.personnel_id) > 1, 1, 0)
)
) AS ex_crew,
SUM(IF(tpi.returningCrew = 1, 1, 0)) AS new_hire
FROM tbl_vessels AS tv
LEFT JOIN tbl_personnel_info AS tpi
ON tv.id = tpi.lastJoinedVsl
LEFT JOIN tbl_contracts AS tc
ON tpi.id = tc.personnel_id
LEFT JOIN tbl_management AS tm
ON tm.id = tv.management
WHERE tpi.emp_status = 'ON-BOARD'
AND tc.status = 'ACTIVE'
AND tv.trade_route = 'WORLD WIDE'
AND tm.management = 'TOKYO'
GROUP BY vesselName;
Aggregate functions can not be nested. So something like SUM(.. COUNT(..) ..) is not possible. You might try something like this:
SELECT tv.id,
tv.vesselName,
CASE WHEN COUNT(tc.personnel_id) > 1
THEN SUM(IF(tpi.returningCrew = 0, 1, 1)
ELSE SUM(IF(tpi.returningCrew = 0, 1, 0)
END AS ex_crew,
SUM(IF(tpi.returningCrew = 1, 1, 0)) AS new_hire
FROM [..]
SUM(IF(tpi.returningCrew = 0, 1, 1) can be rewriten to SUM(1) or to COUNT(*).
SUM(IF(tpi.returningCrew = 0, 1, 0) cann also be rewritten to SUM(tpi.returningCrew = 0)
And SUM(IF(tpi.returningCrew = 1, 1, 0)) to SUM(tpi.returningCrew = 1)
So the final select could be:
SELECT tv.id,
tv.vesselName,
CASE WHEN COUNT(tc.personnel_id) > 1
THEN COUNT(*)
ELSE SUM(tpi.returningCrew = 0)
END AS ex_crew,
SUM(tpi.returningCrew = 1) AS new_hire
FROM [..]

Hive Query issue - Invalid table alias or column reference

I have a query which contains Case statement and the output of the CASE is used to compare another column in Hive.I am not able to run the same query.Here is the query.
SELECT
AL1.RECORD_ID,
AL1.CARRIER_CODE,
AL1.ORIG_AP_CTY_CDE,
AL1.ORIG_STATE_CODE,
AL1.ORIG_COUNTRY_CODE,
AL1.ORIG_GEOGRAPHIC_ZONE_NUMBER,
CASE
WHEN AL1.ORIG_GEOGRAPHIC_ZONE_NUMBER > 99 THEN CONCAT(CAST(AL1.ORIG_GEOGRAPHIC_ZONE_NUMBER/10 AS INT), '0')
WHEN AL1.ORIG_GEOGRAPHIC_ZONE_NUMBER IN ('1','2','4','6','7','8','9') THEN '000'
ELSE AL1.ORIG_GEOGRAPHIC_ZONE_NUMBER
END AS ALL_ORIG_GEOGRAPHIC_ZONE,
AL1.ORIG_WORLD_AREA_NUMBER,
AL1.DEST_AP_CTY_CDE,
AL1.DEST_STATE_CODE,
AL1.DEST_COUNTRY_CODE,
AL1.DEST_GEOGRAPHIC_ZONE_NUMBER,
CASE
WHEN AL1.DEST_GEOGRAPHIC_ZONE_NUMBER > 99 THEN CONCAT(CAST(AL1.DEST_GEOGRAPHIC_ZONE_NUMBER/10 AS INT), '0')
WHEN AL1.DEST_GEOGRAPHIC_ZONE_NUMBER IN ('1','2','4','6','7','8','9') THEN '000'
ELSE AL1.DEST_GEOGRAPHIC_ZONE_NUMBER
END AS ALL_DEST_GEOGRAPHIC_ZONE,
AL1.DEST_WORLD_AREA_NUMBER,
AL1.FRBS_CDE,
AL1.OW_RT_CDE,
AL1.PUB_RULE_TRF_NUM,
AL1.FARE_RULE_NUM,
AL1.PUB_RTG_NUM,
AL1.PUB_FTNTE_ID_CDE,
AL1.FARE_TYPE_CODE,
AL1.SEASON_TYPE_CODE,
AL1.DAY_OF_WEEK_TYPE_CODE,
AL2.CATEGORY_CONTROL_ID,
AL2.CATEGORY_NUMBER AS GROUP_CATEGORY_NUMBER,
AL2.SEQUENCE_NUMBER,
AL2.LOCATION1_TYPE_CODE,
AL2.LOCATION1_CODE,
AL2.LOCATION2_TYPE_CODE,
AL2.LOCATION2_CODE,
AL2.FARE_CLASS_CODE,
AL2.GENERAL_RULE_TARIFF_NUMBER,
AL2.GENERAL_RULE_NUMBER,
AL2.GENERAL_RULE_IND,
'F' AS REC_IND
FROM TMP_TD_CNSTR_WINNING_FARES AL1
INNER JOIN TMP_TD_CNSTRPOST_CAT_CONTROL_ONLY_LIMITED_F AL2
ON (
AL1.CARRIER_CODE=AL2.CARRIER_CODE
AND AL1.PUB_RULE_TRF_NUM=AL2.TARIFF_NUMBER
AND AL1.FARE_RULE_NUM = AL2.RULE_FOOTNOTE_CODE
AND AL1.PUB_RTG_NUM = AL2.ROUTING_NUMBER
AND AL1.SEASON_TYPE_CODE = AL2.SEASON_TYPE_CODE
AND AL1.PUB_FTNTE_ID_CDE = AL2.FOOTNOTE_CODE
AND AL1.OW_RT_CDE = AL2.OW_RT_IND
AND AL1.FARE_TYPE_CODE = AL2.FARE_TYPE_CODE
AND AL1.DAY_OF_WEEK_TYPE_CODE = AL2. DAY_OF_WEEK_TYPE_CODE
)
INNER JOIN TMP_TD_CNSTRPOST_FRBS_MATCH_F AL4
ON ( AL1.CARRIER_CODE = AL4.CARRIER_CODE
AND AL1.PUB_RULE_TRF_NUM = AL4.PUB_RULE_TRF_NUM
AND AL1.FARE_RULE_NUM = AL4.RULE_NUM
AND AL1.FRBS_CDE = AL4.FRBS_CDE
AND AL2.FARE_CLASS_CODE = AL4.FARE_CLASS_CODE
)
WHERE
( (
(COALESCE(LOCATION1_TYPE_CODE, '') = '') OR
(LOCATION1_TYPE_CODE = 'C' AND LOCATION1_CODE = ORIG_AP_CTY_CDE) OR
(LOCATION1_TYPE_CODE = 'S' AND LOCATION1_CODE = ORIG_STATE_CODE) OR
(LOCATION1_TYPE_CODE = 'N' AND LOCATION1_CODE = ORIG_COUNTRY_CODE) OR
(LOCATION1_TYPE_CODE = 'Z' AND LOCATION1_CODE = ORIG_GEOGRAPHIC_ZONE_NUMBER) OR
(LOCATION1_TYPE_CODE = 'Z' AND LOCATION1_CODE = ALL_ORIG_GEOGRAPHIC_ZONE) OR
(LOCATION1_TYPE_CODE = 'A' AND LOCATION1_CODE = ORIG_WORLD_AREA_NUMBER)
)
AND
(
(COALESCE(LOCATION2_TYPE_CODE, '') = '') OR
(LOCATION2_TYPE_CODE = 'C' AND LOCATION2_CODE = DEST_AP_CTY_CDE) OR
(LOCATION2_TYPE_CODE = 'S' AND LOCATION2_CODE = DEST_STATE_CODE) OR
(LOCATION2_TYPE_CODE = 'N' AND LOCATION2_CODE = DEST_COUNTRY_CODE) OR
(LOCATION2_TYPE_CODE = 'Z' AND LOCATION2_CODE = DEST_GEOGRAPHIC_ZONE_NUMBER) OR
(LOCATION2_TYPE_CODE = 'Z' AND LOCATION2_CODE = ALL_DEST_GEOGRAPHIC_ZONE) OR
(LOCATION2_TYPE_CODE = 'A' AND LOCATION2_CODE = DEST_WORLD_AREA_NUMBER)
)
)
OR
((
(COALESCE(LOCATION1_TYPE_CODE, '') = '') OR
(LOCATION1_TYPE_CODE = 'C' AND LOCATION1_CODE = DEST_AP_CTY_CDE) OR
(LOCATION1_TYPE_CODE = 'S' AND LOCATION1_CODE = DEST_STATE_CODE) OR
(LOCATION1_TYPE_CODE = 'N' AND LOCATION1_CODE = DEST_COUNTRY_CODE) OR
(LOCATION1_TYPE_CODE = 'Z' AND LOCATION1_CODE = DEST_GEOGRAPHIC_ZONE_NUMBER) OR
(LOCATION1_TYPE_CODE = 'Z' AND LOCATION1_CODE = ALL_DEST_GEOGRAPHIC_ZONE) OR
(LOCATION1_TYPE_CODE = 'A' AND LOCATION1_CODE = DEST_WORLD_AREA_NUMBER)
)
AND
(
(COALESCE(LOCATION2_TYPE_CODE, '') = '') OR
(LOCATION2_TYPE_CODE = 'C' AND LOCATION2_CODE = ORIG_AP_CTY_CDE) OR
(LOCATION2_TYPE_CODE = 'S' AND LOCATION2_CODE = ORIG_STATE_CODE) OR
(LOCATION2_TYPE_CODE = 'N' AND LOCATION2_CODE = ORIG_COUNTRY_CODE) OR
(LOCATION2_TYPE_CODE = 'Z' AND LOCATION2_CODE = ORIG_GEOGRAPHIC_ZONE_NUMBER) OR
(LOCATION2_TYPE_CODE = 'Z' AND LOCATION2_CODE = ALL_ORIG_GEOGRAPHIC_ZONE) OR
(LOCATION2_TYPE_CODE = 'A' AND LOCATION2_CODE = ORIG_WORLD_AREA_NUMBER)
)
)
;
The error I am encountering is
FAILED: SemanticException [Error 10004]: Line 72:59 Invalid table alias or column reference 'ALL_ORIG_GEOGRAPHIC_ZONE
Please help me resolving the issue.Thanks in Advance!!
The where clause is evaluated before the select clause, so you can't use ALL_DEST_GEOGRAPHIC_ZONE in where clause.
You can try it in a derived table or having clause.
relevant question
Thanks Jerrick.It worked for me using derived table.Here is the updated query.
SELECT
*
FROM (SELECT
AL1.RECORD_ID,
AL1.CARRIER_CODE,
AL1.ORIG_AP_CTY_CDE,
AL1.ORIG_STATE_CODE,
AL1.ORIG_COUNTRY_CODE,
AL1.ORIG_GEOGRAPHIC_ZONE_NUMBER,
CASE
WHEN AL1.ORIG_GEOGRAPHIC_ZONE_NUMBER > 99 THEN CONCAT((CAST(AL1.ORIG_GEOGRAPHIC_ZONE_NUMBER / 10 AS int)), '0')
WHEN AL1.ORIG_GEOGRAPHIC_ZONE_NUMBER IN ('1', '2', '4', '6', '7', '8', '9') THEN '000'
ELSE AL1.ORIG_GEOGRAPHIC_ZONE_NUMBER
END AS ALL_ORIG_GEOGRAPHIC_ZONE,
AL1.ORIG_WORLD_AREA_NUMBER,
AL1.DEST_AP_CTY_CDE,
AL1.DEST_STATE_CODE,
AL1.DEST_COUNTRY_CODE,
AL1.DEST_GEOGRAPHIC_ZONE_NUMBER,
CASE
WHEN AL1.DEST_GEOGRAPHIC_ZONE_NUMBER > 99 THEN CONCAT((CAST(AL1.DEST_GEOGRAPHIC_ZONE_NUMBER / 10 AS int)), '0')
WHEN AL1.DEST_GEOGRAPHIC_ZONE_NUMBER IN ('1', '2', '4', '6', '7', '8', '9') THEN '000'
ELSE AL1.DEST_GEOGRAPHIC_ZONE_NUMBER
END AS ALL_DEST_GEOGRAPHIC_ZONE,
AL1.DEST_WORLD_AREA_NUMBER,
AL1.FRBS_CDE,
AL1.OW_RT_CDE,
AL1.PUB_RULE_TRF_NUM,
AL1.FARE_RULE_NUM,
AL1.PUB_RTG_NUM,
AL1.PUB_FTNTE_ID_CDE,
AL1.FARE_TYPE_CODE,
AL1.SEASON_TYPE_CODE,
AL1.DAY_OF_WEEK_TYPE_CODE,
AL2.CATEGORY_CONTROL_ID,
AL2.CATEGORY_NUMBER AS GROUP_CATEGORY_NUMBER,
AL2.SEQUENCE_NUMBER,
AL2.LOCATION1_TYPE_CODE,
AL2.LOCATION1_CODE,
AL2.LOCATION2_TYPE_CODE,
AL2.LOCATION2_CODE,
AL2.FARE_CLASS_CODE,
AL2.GENERAL_RULE_TARIFF_NUMBER,
AL2.GENERAL_RULE_NUMBER,
AL2.GENERAL_RULE_IND,
'F' AS REC_IND
FROM TMP_TD_CNSTR_WINNING_FARES AL1
INNER JOIN TMP_TD_CNSTRPOST_CAT_CONTROL_ONLY_LIMITED_F AL2
ON (
AL1.CARRIER_CODE = AL2.CARRIER_CODE
AND AL1.PUB_RULE_TRF_NUM = AL2.TARIFF_NUMBER
AND AL1.FARE_RULE_NUM = AL2.RULE_FOOTNOTE_CODE
AND AL1.PUB_RTG_NUM = AL2.ROUTING_NUMBER
AND AL1.SEASON_TYPE_CODE = AL2.SEASON_TYPE_CODE
AND AL1.PUB_FTNTE_ID_CDE = AL2.FOOTNOTE_CODE
AND AL1.OW_RT_CDE = AL2.OW_RT_IND
AND AL1.FARE_TYPE_CODE = AL2.FARE_TYPE_CODE
AND AL1.DAY_OF_WEEK_TYPE_CODE = AL2.DAY_OF_WEEK_TYPE_CODE
)
INNER JOIN TMP_TD_CNSTRPOST_FRBS_MATCH_F AL4
ON (AL1.CARRIER_CODE = AL4.CARRIER_CODE
AND AL1.PUB_RULE_TRF_NUM = AL4.PUB_RULE_TRF_NUM
AND AL1.FARE_RULE_NUM = AL4.RULE_NUM
AND AL1.FRBS_CDE = AL4.FRBS_CDE
AND AL2.FARE_CLASS_CODE = AL4.FARE_CLASS_CODE
)) AS WF
WHERE ((
(COALESCE(LOCATION1_TYPE_CODE, '') = '')
OR (LOCATION1_TYPE_CODE = 'C'
AND LOCATION1_CODE = ORIG_AP_CTY_CDE)
OR (LOCATION1_TYPE_CODE = 'S'
AND LOCATION1_CODE = ORIG_STATE_CODE)
OR (LOCATION1_TYPE_CODE = 'N'
AND LOCATION1_CODE = ORIG_COUNTRY_CODE)
OR (LOCATION1_TYPE_CODE = 'Z'
AND LOCATION1_CODE = ORIG_GEOGRAPHIC_ZONE_NUMBER)
OR (LOCATION1_TYPE_CODE = 'Z'
AND LOCATION1_CODE = WF.ALL_ORIG_GEOGRAPHIC_ZONE)
OR (LOCATION1_TYPE_CODE = 'A'
AND LOCATION1_CODE = ORIG_WORLD_AREA_NUMBER)
)
AND (
(COALESCE(LOCATION2_TYPE_CODE, '') = '')
OR (LOCATION2_TYPE_CODE = 'C'
AND LOCATION2_CODE = DEST_AP_CTY_CDE)
OR (LOCATION2_TYPE_CODE = 'S'
AND LOCATION2_CODE = DEST_STATE_CODE)
OR (LOCATION2_TYPE_CODE = 'N'
AND LOCATION2_CODE = DEST_COUNTRY_CODE)
OR (LOCATION2_TYPE_CODE = 'Z'
AND LOCATION2_CODE = DEST_GEOGRAPHIC_ZONE_NUMBER)
OR (LOCATION2_TYPE_CODE = 'Z'
AND LOCATION2_CODE = WF.ALL_DEST_GEOGRAPHIC_ZONE)
OR (LOCATION2_TYPE_CODE = 'A'
AND LOCATION2_CODE = DEST_WORLD_AREA_NUMBER)
)
)
OR ((
(COALESCE(LOCATION1_TYPE_CODE, '') = '')
OR (LOCATION1_TYPE_CODE = 'C'
AND LOCATION1_CODE = DEST_AP_CTY_CDE)
OR (LOCATION1_TYPE_CODE = 'S'
AND LOCATION1_CODE = DEST_STATE_CODE)
OR (LOCATION1_TYPE_CODE = 'N'
AND LOCATION1_CODE = DEST_COUNTRY_CODE)
OR (LOCATION1_TYPE_CODE = 'Z'
AND LOCATION1_CODE = DEST_GEOGRAPHIC_ZONE_NUMBER)
OR (LOCATION1_TYPE_CODE = 'Z'
AND LOCATION1_CODE = WF.ALL_DEST_GEOGRAPHIC_ZONE)
OR (LOCATION1_TYPE_CODE = 'A'
AND LOCATION1_CODE = DEST_WORLD_AREA_NUMBER)
)
AND (
(COALESCE(LOCATION2_TYPE_CODE, '') = '')
OR (LOCATION2_TYPE_CODE = 'C'
AND LOCATION2_CODE = ORIG_AP_CTY_CDE)
OR (LOCATION2_TYPE_CODE = 'S'
AND LOCATION2_CODE = ORIG_STATE_CODE)
OR (LOCATION2_TYPE_CODE = 'N'
AND LOCATION2_CODE = ORIG_COUNTRY_CODE)
OR (LOCATION2_TYPE_CODE = 'Z'
AND LOCATION2_CODE = ORIG_GEOGRAPHIC_ZONE_NUMBER)
OR (LOCATION2_TYPE_CODE = 'Z'
AND LOCATION2_CODE = WF.ALL_ORIG_GEOGRAPHIC_ZONE)
OR (LOCATION2_TYPE_CODE = 'A'
AND LOCATION2_CODE = ORIG_WORLD_AREA_NUMBER)
)
)
;

How use MAX in mysql to get follow result

This is the query
SELECT research_id,
IF(product_id = 4, IF(value REGEXP '^-?[0-9]+$' > 0, value, IF(value = 'Yes', 1, 0)), 0) AS val1,
IF(product_id = 8, IF(value REGEXP '^-?[0-9]+$' > 0, value, IF(value = 'Yes', 1, 0)), 0) AS val2
FROM research_product_details rpd
LEFT JOIN products p
ON rpd.product_id = p.id
WHERE (product_id = 4 AND value >= 50) OR (product_id = 8 AND value >= 50)
ORDER BY research_id ASC , product_id ASC
And i got this result from this query
i want it like follow
As #Jkike mentioned in his comment, one way to achieve what you want is to simply wrap your current query and GROUP BY the research_id column, selecting the max value for the val1 and val2 columns:
SELECT t.research_id AS research_id, MAX(t.val1) AS val1, MAX(t.val2) AS val2
FROM
(
SELECT research_id,
IF(product_id = 4, IF(value REGEXP '^-?[0-9]+$' > 0, value, IF(value = 'Yes', 1, 0)), 0) AS val1,
IF(product_id = 8, IF(value REGEXP '^-?[0-9]+$' > 0, value, IF(value = 'Yes', 1, 0)), 0) AS val2
FROM research_product_details rpd
LEFT JOIN products p
ON rpd.product_id = p.id
WHERE (product_id = 4 AND value >= 50) OR (product_id = 8 AND value >= 50)
ORDER BY research_id ASC , product_id ASC
) AS t
GROUP BY t.research_id

TSQL Group, Count and Sum dataset not giving expected result

Say I have a query that returns none grouped data, as the first query below does, and I wish to group the data by summing and counting some fields and grouping on the remaining fields, as shown in the second query.
Why in this case do the count fields return 2 instead of the expected 1?
EDIT:
I have just realized its counting distinct rows so in the RequestsOnSite it has 114065 and 0 resulting in a count of 2. Is there a way to discount 0 valued cells?
Query:
SELECT 'Month' AS [Period],
ISNULL(Zone.ZoneID,'') AS ZoneID,
ISNULL(Zone.ZoneName,'') AS ZoneName,
ISNULL(Region.RegionCode,'') AS RegionCode,
ISNULL(Region.RegionName,'') AS RegionName,
Branch.BranchID,
ISNULL(Branch.BranchName,'') AS BranchName,
SR01.ServicingRep,
ISNULL(LCRep.RepName,'') AS RepName,
CASE WHEN ProductivityRequests.RequestType <> 'MN' AND (ProductivityRequests.OnOffSite = 'ON' OR ProductivityRequests.OnOffSiteSvc = 'ON') THEN ProductivityRequests.ReportKey ELSE 0 END AS RequestsOnSite,
CASE WHEN ProductivityHours.RequestType <> 'MN' AND (ProductivityHours.OnOffSite = 'ON' OR ProductivityHours.OnOffSiteSvc = 'ON') THEN ProductivityHours.TotalOnSiteTime ELSE 0 END AS HoursOnSite,
CASE WHEN ProductivityRequests.RequestType <> 'MN' AND (ProductivityRequests.OnOffSite = 'OF' OR ProductivityRequests.OnOffSiteSvc = 'OF') THEN ProductivityRequests.ReportKey ELSE 0 END AS RequestsOffSite,
CASE WHEN ProductivityHours.RequestType <> 'MN' AND (ProductivityHours.OnOffSite = 'OF' OR ProductivityHours.OnOffSiteSvc = 'OF') THEN ProductivityHours.TotalOffSiteTime ELSE 0 END AS HoursOffSite,
CASE WHEN (ProductivityRequests.RequestType = 'NR') THEN ProductivityRequests.ReportKey ELSE 0 END AS RequestsNonReport,
CASE WHEN (ProductivityHours.RequestType = 'NR') THEN ProductivityHours.TotalNonReportTime ELSE 0 END AS HoursNonReport,
ProductivityRequests.OnOffSite,
ProductivityRequests.OnOffSiteSvc
FROM SR01
INNER JOIN ProductivityHours ON ProductivityHours.ReportKey = SR01.ReportKey
INNER JOIN ProductivityRequests ON ProductivityRequests.ReportKey = SR01.ReportKey
LEFT JOIN LCRep ON SR01.ServicingRep = LCRep.RepID
LEFT JOIN Branch ON SR01.ServicingBranch = Branch.BranchID
LEFT JOIN Region ON Region.RegionCode = Branch.Region
LEFT JOIN Zone ON Zone.ZoneAbbrev = Region.Zone
WHERE ISNULL(SR01.ServicingBranch,'-') <> '-'
AND SR01.[Status]='X'
AND SR01.DateComplete BETWEEN DATEADD(month, DATEDIFF(month, 0, #DateTo), 0) AND #DateTo
AND Zone.ZoneID IN (#Zone)
AND Region.RegionCode IN (#Region)
AND Branch.BranchID IN (#Branch)
AND LCRep.RepID IN(#RepID)
AND (#EquipmentBreakdown = 0 OR (#EquipmentBreakdown = 1 AND #PropertyCasualty = 1) OR (LCRep.EB = #EquipmentBreakdown))
AND (#PropertyCasualty = 0 OR (#EquipmentBreakdown = 1 AND #PropertyCasualty = 1) OR (LCRep.PC = #PropertyCasualty))
NOTE: OnOffSite and OnOffSiteSvc are shown here just for clarity and will not appear in the final query.
Resultset
Aggregate query
SELECT 'Month' AS [Period],
ISNULL(Zone.ZoneID,'') AS ZoneID,
ISNULL(Zone.ZoneName,'') AS ZoneName,
ISNULL(Region.RegionCode,'') AS RegionCode,
ISNULL(Region.RegionName,'') AS RegionName,
Branch.BranchID,
ISNULL(Branch.BranchName,'') AS BranchName,
SR01.ServicingRep,
ISNULL(LCRep.RepName,'') AS RepName,
COUNT(DISTINCT CASE WHEN ProductivityRequests.RequestType <> 'MN' AND (ProductivityRequests.OnOffSite = 'ON' OR ProductivityRequests.OnOffSiteSvc = 'ON') THEN ProductivityRequests.ReportKey ELSE 0 END) AS RequestsOnSite,
SUM(DISTINCT CASE WHEN ProductivityHours.RequestType <> 'MN' AND (ProductivityHours.OnOffSite = 'ON' OR ProductivityHours.OnOffSiteSvc = 'ON') THEN ProductivityHours.TotalOnSiteTime ELSE 0 END) AS HoursOnSite,
COUNT(DISTINCT CASE WHEN ProductivityRequests.RequestType <> 'MN' AND (ProductivityRequests.OnOffSite = 'OF' OR ProductivityRequests.OnOffSiteSvc = 'OF') THEN ProductivityRequests.ReportKey ELSE 0 END) AS RequestsOffSite,
SUM(DISTINCT CASE WHEN ProductivityHours.RequestType <> 'MN' AND (ProductivityHours.OnOffSite = 'OF' OR ProductivityHours.OnOffSiteSvc = 'OF') THEN ProductivityHours.TotalOffSiteTime ELSE 0 END) AS HoursOffSite,
COUNT(DISTINCT CASE WHEN (ProductivityRequests.RequestType = 'NR') THEN ProductivityRequests.ReportKey ELSE 0 END) AS RequestsNonReport,
SUM(DISTINCT CASE WHEN (ProductivityHours.RequestType = 'NR') THEN ProductivityHours.TotalNonReportTime ELSE 0 END) AS HoursNonReport
FROM SR01
INNER JOIN ProductivityHours ON ProductivityHours.ReportKey = SR01.ReportKey
INNER JOIN ProductivityRequests ON ProductivityRequests.ReportKey = SR01.ReportKey
LEFT JOIN LCRep ON SR01.ServicingRep = LCRep.RepID
LEFT JOIN Branch ON SR01.ServicingBranch = Branch.BranchID
LEFT JOIN Region ON Region.RegionCode = Branch.Region
LEFT JOIN Zone ON Zone.ZoneAbbrev = Region.Zone
WHERE ISNULL(SR01.ServicingBranch,'-') <> '-'
AND SR01.[Status]='X'
AND SR01.DateComplete BETWEEN DATEADD(month, DATEDIFF(month, 0, #DateTo), 0) AND #DateTo
AND Zone.ZoneID IN (#Zone)
AND Region.RegionCode IN (#Region)
AND Branch.BranchID IN (#Branch)
AND LCRep.RepID IN(#RepID)
AND (#EquipmentBreakdown = 0 OR (#EquipmentBreakdown = 1 AND #PropertyCasualty = 1) OR (LCRep.EB = #EquipmentBreakdown))
AND (#PropertyCasualty = 0 OR (#EquipmentBreakdown = 1 AND #PropertyCasualty = 1) OR (LCRep.PC = #PropertyCasualty))
GROUP BY Zone.ZoneID, Zone.ZoneName, Region.RegionCode, Region.RegionName, Branch.BranchID, BranchName, SR01.ServicingRep, LCRep.RepName
Resultset:
Note that the RequestsOnSite, RequestsOffSite and RequestsNonReport all contain 2 rather than the expected 1.
OK, the answer was to use the NullIF operator as discussed in this Stack Overflow question
The resultant query would look like this
SELECT 'Month' AS [Period],
ISNULL(Zone.ZoneID,'') AS ZoneID,
ISNULL(Zone.ZoneName,'') AS ZoneName,
ISNULL(Region.RegionCode,'') AS RegionCode,
ISNULL(Region.RegionName,'') AS RegionName,
Branch.BranchID,
ISNULL(Branch.BranchName,'') AS BranchName,
SR01.ServicingRep,
ISNULL(LCRep.RepName,'') AS RepName,
COUNT(DISTINCT CASE WHEN ProductivityRequests.RequestType <> 'MN' AND (ProductivityRequests.OnOffSite = 'ON' OR ProductivityRequests.OnOffSiteSvc = 'ON') THEN NULLIF(ProductivityRequests.ReportKey, 0) ELSE NULL END) AS RequestsOnSite,
SUM(DISTINCT CASE WHEN ProductivityHours.RequestType <> 'MN' AND (ProductivityHours.OnOffSite = 'ON' OR ProductivityHours.OnOffSiteSvc = 'ON') THEN ProductivityHours.TotalOnSiteTime ELSE 0 END) AS HoursOnSite,
COUNT(DISTINCT CASE WHEN ProductivityRequests.RequestType <> 'MN' AND (ProductivityRequests.OnOffSite = 'OF' OR ProductivityRequests.OnOffSiteSvc = 'OF') THEN NULLIF(ProductivityRequests.ReportKey, 0) ELSE NULL END) AS RequestsOffSite,
SUM(DISTINCT CASE WHEN ProductivityHours.RequestType <> 'MN' AND (ProductivityHours.OnOffSite = 'OF' OR ProductivityHours.OnOffSiteSvc = 'OF') THEN ProductivityHours.TotalOffSiteTime ELSE 0 END) AS HoursOffSite,
COUNT(DISTINCT CASE WHEN (ProductivityRequests.RequestType = 'NR') THEN NULLIF(ProductivityRequests.ReportKey, 0) ELSE NULL END) AS RequestsNonReport,
SUM(DISTINCT CASE WHEN (ProductivityHours.RequestType = 'NR') THEN ProductivityHours.TotalNonReportTime ELSE 0 END) AS HoursNonReport
FROM SR01
INNER JOIN ProductivityHours ON ProductivityHours.ReportKey = SR01.ReportKey
INNER JOIN ProductivityRequests ON ProductivityRequests.ReportKey = SR01.ReportKey
LEFT JOIN LCRep ON SR01.ServicingRep = LCRep.RepID
LEFT JOIN Branch ON SR01.ServicingBranch = Branch.BranchID
LEFT JOIN Region ON Region.RegionCode = Branch.Region
LEFT JOIN Zone ON Zone.ZoneAbbrev = Region.Zone
WHERE ISNULL(SR01.ServicingBranch,'-') <> '-'
AND SR01.[Status]='X'
AND SR01.DateComplete BETWEEN DATEADD(month, DATEDIFF(month, 0, #DateTo), 0) AND #DateTo
AND Zone.ZoneID IN (#Zone)
AND Region.RegionCode IN (#Region)
AND Branch.BranchID IN (#Branch)
AND LCRep.RepID IN(#RepID)
AND (#EquipmentBreakdown = 0 OR (#EquipmentBreakdown = 1 AND #PropertyCasualty = 1) OR (LCRep.EB = #EquipmentBreakdown))
AND (#PropertyCasualty = 0 OR (#EquipmentBreakdown = 1 AND #PropertyCasualty = 1) OR (LCRep.PC = #PropertyCasualty))
GROUP BY Zone.ZoneID, Zone.ZoneName, Region.RegionCode, Region.RegionName, Branch.BranchID, BranchName, SR01.ServicingRep, LCRep.RepName