I would like to condition when to GROUP_CONCAT my results. I can't figure out the way how to separate my 'category' and 'condition' results.
SELECT d.company_name AS 'organisation name',
GROUP_CONCAT(DISTINCT tag.tag) AS 'category',
GROUP_CONCAT(DISTINCT tag.tag) AS 'conditions', d.contact_describtion AS 'description', d.tel, d.tel2, d.mobile, d.email, d.email2, d.web, d.web2, d.address, d.town, d.county, d.post_code AS 'post code', IF(d.state = 1, "published", "unpublished") AS 'status',d.contact_page_notes AS 'contact history', d.last_contacted_date AS 'last contacted', d.last_updated_date AS 'last updated'
FROM jds4a_directory d INNER JOIN
jds4a_tags_resources res
on d.id = res.resource_id INNER JOIN
jds4a_tags tag
on tag.id = res.tag_id
WHERE tag.category = 'condition' OR tag.category = 'category'
GROUP BY res.resource_id
What I want to achieve is to only display category tags under the category and only display condition tags under conditions
Use case. You are also returning way too many columns, I think:
SELECT d.company_name AS organisation_name,
GROUP_CONCAT(DISTINCT (CASE WHEN tag.category = 'condition' THEN tag.tag END)) AS categories,
GROUP_CONCAT(DISTINCT (CASE WHEN tag.category = 'category' THEN tag.tag END)) AS conditions
FROM jds4a_directory d INNER JOIN
jds4a_tags_resources res
on d.id = res.resource_id INNER JOIN
jds4a_tags tag
on tag.id = res.tag_id
WHERE tag.category IN ('condition', 'category')
GROUP BY d.company_name;
Notes:
The SELECT columns should be consistent with the GROUP BY columns. Don't overload with extraneous columns.
GROUP BY should match the unaggregated keys/expressions in the SELECT.
Use IN instead of a bunch of ORs -- easier to maintain, write, and less prone to error.
Use single quotes for string and date constants. Don't use them for column aliases.
You can try below Query:
SELECT d.company_name AS 'organisation name',
GROUP_CONCAT(DISTINCT tag.tag) AS 'category',
GROUP_CONCAT(DISTINCT tag1.tag) AS 'conditions', d.contact_describtion AS 'description', d.tel, d.tel2, d.mobile, d.email, d.email2, d.web, d.web2, d.address, d.town, d.county, d.post_code AS 'post code', IF(d.state = 1, "published", "unpublished") AS 'status',d.contact_page_notes AS 'contact history', d.last_contacted_date AS 'last contacted', d.last_updated_date AS 'last updated'
FROM jds4a_directory d
INNER JOIN jds4a_tags_resources res
on d.id = res.resource_id
LEFT JOIN jds4a_tags tag
on tag.id = res.tag_id AND tag.category = 'category'
LEFT JOIN jds4a_tags tag1
on tag1.id = res.tag_id AND tag1.category = 'condition'
GROUP BY res.resource_id
Have not tried this query. But it should work. Basically you need to join on jds4a_tags table one more time with conditional tag name
Related
Novice would greatly appreciate assistance on the following 3706 error message:
expected something between the word 'Calls' and the 'case' keyword
SELECT distinct
b.emp_nbr,
b.prim_terr_desc,
a.sales_terr_nbr,
TRIM (B.first_nm) ||' '|| TRIM (B.last_nm) as AE_Name,
count (distinct call_nbr) as Calls
case (when a.sale_call_chanl_desc LIKE 'Face to Face%' then 'F2F'
when a.sale_call_chanl_desc = 'Telephone' then 'Phone'
when a.sale_call_chanl_desc LIKE 'Web Meeting%' then 'Web_Meeting'
end) as Channel
FROM isell_prod_view_db.sfdc_call_action a
LEFT OUTER JOIN isell_prod_view_db.sfdc_customer_info c ON (a.cust_acct_nbr = c.cust_acct_nbr and a.rec_delt_flg = 'N')
LEFT OUTER JOIN isell_prod_view_db.sfdc_opportunity d ON (d.cust_acct_nbr = c.cust_acct_nbr and d.delt_flg = 'N')
LEFT OUTER JOIN isell_prod_view_db.sfdc_user_profile b ON a.crte_by_user_key_nbr = b.user_key_nbr
LEFT OUTER JOIN isell_prod_view_db.sfdc_opportunity_item e ON (e.oprty_key_nbr = d.oprty_key_nbr and e.delt_flg = 'N')
where a.sale_call_stat_desc = 'Completed'
and a.sales_div_nbr = '8'
and a.sales_grp_nbr = '9'
and a.sales_org_nbr ='30'
and b.prim_terr_desc LIKE ('8-9-30%')
and a.priv_entr_flg='N'
and a.sale_call_chanl_desc is not null
and CAST(a.call_dt AS date format 'MM/DD/YYYY') between '06/01/2019' and '05/31/2020'
group by 1,2,3,4
I rejigged the code. This works. I think i needed a comma after "AS Channel"
SELECT distinct
b.emp_nbr,
TRIM (B.first_nm) ||' '|| TRIM (B.last_nm) as AE_Name,
b.prim_terr_desc,
b.prim_terr_seg_nbr,
case when CAST(a.call_dt AS date format 'MM/DD/YYYY') between '12/01/2019' and '02/29/2020' then 'Q3'
when CAST(a.call_dt AS date format 'MM/DD/YYYY') between '03/01/2020' and '05/31/2020' then 'Q4'
end as Qtr,
count (distinct call_nbr) as Calls
FROM isell_prod_view_db.sfdc_call_action a
LEFT OUTER JOIN isell_prod_view_db.sfdc_customer_info c ON (a.cust_acct_nbr = c.cust_acct_nbr and a.rec_delt_flg = 'N')
LEFT OUTER JOIN isell_prod_view_db.sfdc_opportunity d ON (d.cust_acct_nbr = c.cust_acct_nbr and d.delt_flg = 'N')
LEFT OUTER JOIN isell_prod_view_db.sfdc_user_profile b ON a.crte_by_user_key_nbr = b.user_key_nbr
LEFT OUTER JOIN isell_prod_view_db.sfdc_opportunity_item e ON (e.oprty_key_nbr = d.oprty_key_nbr and e.delt_flg = 'N')
where a.sale_call_stat_desc = 'Completed'
and a.sales_div_nbr = '8'
and a.sales_grp_nbr = '9'
and a.sales_org_nbr ='30'
and b.prim_terr_desc LIKE ('8-9-30%')
and A.rec_delt_flg = 'N'
and A.child_event_flg='N'
and a.priv_entr_flg='N'
and B.prim_terr_seg_desc not in ('No Coverage')
and A.sale_call_chanl_desc in ('Telephone', 'Phone', 'Face to Face - Appt', 'Face to Face - No Appt', 'Web Meeting')
and B.prim_terr_seg_nbr not in ('3', '8', '25')
and CAST(a.call_dt AS date format 'MM/DD/YYYY') between '12/01/2019' and '05/31/2020'
group by 1,2,3,4,5
Please help me to optimize below Query -
SELECT DISTINCT
al.displayName AS 'Brand',
al.locationName AS 'Campus',
pg.groupName AS 'School Phase',
result.programName AS 'Grade',
pc.categoryName AS 'Grade Category',
result.batchName AS 'Intake',
result.periodName AS 'Period',
admission.id AS 'ADmission',
result.stdName AS 'Student Name',
usr.code AS 'Student Id',
result.courseName AS 'Subject',
result.courseVariant AS 'Subject Variant',
cc.categoryName AS 'Subject Category',
fac.printName AS 'Teacher',
result.planPrintName AS 'Scheme',
planRank.marksObtainedFrom AS 'Maximum Marks',
planRank.gradeObtainedFrom AS 'Maximum Grade',
planRank.obtainedMarks AS 'Subject Level Marks',
planRank.grade AS 'Subject Grade',
planRank.obtainedMarks AS 'Percentage',
planRank.status AS 'Result Status',
result.levelOnePrintName AS 'Type',
typeRank.effectiveMarks AS 'Type Marks',
typeRank.grade AS 'Type Grade',
typeRank.status AS 'Type Result Status',
result.levelTwoPrintName AS 'Sub Type',
subTypeRank.effectiveMarks AS 'Sub Type Marks',
subTypeRank.grade AS 'Sub Type Grade',
subTypeRank.status AS 'Sub Type Result Status',
result.levelThreePrintName AS 'Method',
result.effectiveMarks AS 'Method Marks',
result.grade AS 'Method Grade',
result.status AS 'Method Result Status',
CASE
WHEN evntDetail.eventName IS NULL THEN evnt.detailSequenceNumber
WHEN evntDetail.eventName IS NOT NULL THEN evntDetail.eventName
ELSE NULL
END AS 'Event',
eventMarks.effectiveMarks AS 'Event Marks',
eventMarks.finalGrade AS 'Event Grade'
FROM
marksheet AS result
INNER JOIN
admission AS admission ON admission.id = result.admissionId
INNER JOIN
users AS usr ON usr.id = result.studentId
INNER JOIN
academy_location AS al ON al.id = admission.academyLocationId
INNER JOIN
programs AS prgm ON prgm.id = result.programId
LEFT OUTER JOIN
program_group AS pg ON pg.id = prgm.programGroupId
LEFT OUTER JOIN
program_category AS pc ON pc.id = prgm.programCategoryId
LEFT OUTER JOIN
courses AS course ON course.id = result.courseId
LEFT OUTER JOIN
course_category AS cc ON cc.id = course.courseCategoryId
LEFT OUTER JOIN
program_batch_course_param AS param ON result.courseVariantId = param.courseVarientId
AND result.periodId = param.progBatchPeriodConfigId
LEFT OUTER JOIN
prog_batch_course_faculty AS pbcf ON pbcf.progBatchCourseParamId = param.id
LEFT OUTER JOIN
users AS fac ON fac.id = pbcf.facultyId
LEFT OUTER JOIN
evaluation_plan_rank AS planRank ON result.admissionId = planRank.admissionId
AND (result.courseVariantId = planRank.courseVariantId
OR planRank.courseVariantId IS NULL)
AND result.sectionId = planRank.sectionId
AND result.periodId = planRank.periodId
AND result.evaluationPlanId = planRank.evaluationPlanId
LEFT OUTER JOIN
evaluation_plan_level_one_rank AS typeRank ON result.admissionId = typeRank.admissionId
AND (result.courseVariantId = typeRank.courseVariantId
OR typeRank.courseVariantId IS NULL)
AND result.periodId = typeRank.periodId
AND result.sectionId = typeRank.sectionId
AND result.evaluationPlanLevelOneId = typeRank.evaluationPlanLevelOneId
LEFT OUTER JOIN
evaluation_plan_level_two_rank AS subTypeRank ON result.admissionId = subTypeRank.admissionId
AND (result.courseVariantId = subTypeRank.courseVariantId)
AND result.periodId = subTypeRank.periodId
AND result.sectionId = subTypeRank.sectionId
AND result.evaluationPlanLevelTwoId = subTypeRank.evaluationPlanLevelTwoId
INNER JOIN
eval_seq_detail AS evnt ON result.evaluationPlanThreeId = evnt.evalSequenceId
LEFT OUTER JOIN
examination_result AS eventMarks ON result.admissionId = eventMarks.admissionId
AND (result.courseVariantId = eventMarks.courseVariantId
OR eventMarks.courseVariantId IS NULL)
AND result.sectionId = eventMarks.sectionId
AND result.periodId = eventMarks.periodId
AND evnt.id = eventMarks.evaluationDetailSequenceId
LEFT OUTER JOIN
evaluation_type_course typeCourse ON eventMarks.courseVariantId = typeCourse.courseVariantId
AND eventMarks.periodId = typeCourse.periodId
LEFT OUTER JOIN
exam_event_detail evntDetail ON eventMarks.evaluationDetailSequenceId = evntDetail.eventId
AND evntDetail.evaluationTypeCourseId = typeCourse.id
WHERE
eventMarks.examResultStatus IS NOT NULL
AND result.evaluationPlanId IS NOT NULL
AND result.evaluationPlanLevelOneId IS NOT NULL
AND result.evaluationPlanLevelTwoId IS NOT NULL
AND result.evaluationPlanThreeId IS NOT NULL;
In tables marksheet = '740119' and examination_result = '4891575' approx records.
when I execute query then it will take around 10 min and also show time out error, as data-set is large.
I applied indexes on table's for performance but still Query take lots of time.
I applied Explain on Query to check status -
Add the keyword "STRAIGHT_JOIN" to you query. It looks like you have everything in proper logical alignment. You are querying from the main table and joining to all the lookup tables secondary. MySQL sometimes tries to optimize based on table row sizes and will look at a smaller table as a more beneficial path and can choke.
SELECT STRAIGHT_JOIN (rest of query)
Tells MySQL to do the query in the order you provided, don't think for me.
Now, that said, you don't really have a WHERE clause that may be taking advantage of an index. To prevent the need of having to go to every data page for the records, if you have an index on the where clauses, the engine can pre-qualify those records where not null via the index. Assuming that each evaluation plan is an integer (numeric) based "ID" value, I would add an index on
( evaluationPlanId, evaluationPlanLevelOneId, evaluationPlanLevelTwoId, evaluationPlanThreeId )
I am trying to group by a substring. I only get the one result:
Region = Coastal, Value (R) = 1144900.
I am supposed to get 2 results.
This is my code:
SELECT
DISTINCT SUBSTRING_INDEX(`team_name`, '-', 1) AS 'Region',
SUM(`opportunities`.`value`) AS 'Value (R)'
FROM
`opportunities`
LEFT JOIN cf_type_link_data ON cf_type_link_data.sourceid = opportunities.id
LEFT JOIN cf_lu_type_fields ON cf_type_link_data.fieldid = cf_lu_type_fields.id
LEFT JOIN cf_lu_types_fields_dropdown ON cf_type_link_data.`value` = cf_lu_types_fields_dropdown.id AND cf_lu_type_fields.id = cf_lu_types_fields_dropdown.fieldid
LEFT JOIN `lu_teams` ON `lu_teams`.`contactid` = `opportunities`.`user_allocation`
LEFT JOIN `teams` ON `teams`.`id` = `lu_teams`.`teamid`
LEFT JOIN `lu_opportunity_status` ON `lu_opportunity_status`.`id` = `opportunities`.`status`
WHERE 1
AND `cf_lu_types_fields_dropdown`.`values` = 'Building Project'
AND cf_lu_type_fields.fieldname = 'Scaffolding Segment'
AND (`opportunities`.`expecteddate` >= '2012-01-01' AND `opportunities`.`expecteddate` <= '2012-07-24')
GROUP BY 'Region'
ORDER BY cf_lu_types_fields_dropdown.`values`;
Any help is appreciated.
You can not use same alias from select in GROUP BY clause
try
SELECT DISTINCT SUBSTRING_INDEX(team_name, '-', 1) AS 'Region',
SUM(opportunities.value) AS 'Value (R)'....
GROUP BY SUBSTRING_INDEX(team_name, '-', 1)
ORDER BY cf_lu_types_fields_dropdown.values;
Try not to use quotes for field identifiers -
'Region' -> Region
In your case you see only one record in result data set because you group by string 'Region', but you should group by value(s).
I'm having some difficulty with my SQL statement. I'm doing a query on WordPress to display posts based on multiple post meta fields. When I do the query and filter with only one meta field, or a OR on multiple it works, however AND on multiple fails.
SELECT wposts . *
FROM wp_posts wposts
INNER JOIN (
SELECT post_id
FROM wp_postmeta wpostmeta
WHERE (
(wpostmeta.meta_key = 'ulnooweg_business_industry'
AND wpostmeta.meta_value = 'Legal Services')
AND (
wpostmeta.meta_key = 'ulnooweg_business_province'
AND wpostmeta.meta_value = 'New Brunswick')
)
GROUP BY post_id
)
AS t ON t.post_id = wposts.ID
WHERE wposts.post_status = 'publish'
AND wposts.post_type = 'business'
ORDER BY wposts.post_title ASC
LIMIT 0 , 30
Your query is testing if meta_key (and meta_value) is 2 different values in the same row, which is impossible. But I see what you are trying to do..
Try joining the wp_postmeta table twice except each with an ON clause that excludes all rows except those that satisfy the meta_key condition:
SELECT
p.*,
GROUP_CONCAT(CONCAT(pm.meta_key,':',pm.meta_value) SEPARATOR ',') AS meta_values
FROM
wp_posts p
JOIN wp_postmeta pm ON pm.post_id = p.ID
JOIN wp_postmeta pm_bi ON (pm_bi.post_id = p.ID AND pm_bi.meta_key = 'ulnooweg_business_industry')
JOIN wp_postmeta pm_bp ON (pm_bp.post_id = p.ID AND pm_bp.meta_key = 'ulnooweg_business_province')
WHERE
pm_bi.meta_value = 'Legal Services'
AND pm_bp.meta_value = 'New Brunswick'
AND p.post_type = 'business'
AND p.post_status = 'publish'
GROUP BY p.ID
ORDER BY p.post_title ASC
Note: I joined the wp_postmeta table 3 times here to help prove that the conditions are satisfied, but you can remove the GROUP_CONCAT line (and the comma on the previous line of course) and the first JOIN to wp_postmeta and the query will work the same.
In the subquery, it looks like it's looking for records where both wpostmeta.meta_key = 'ulnooweg_business_industry' and wpostmeta.meta_key = 'ulnooweg_business_province' -- in other words, wpostmeta.meta_key needs to be equal to two strings simultaneously to satisfy this condition. Also, it's looking for wpostmeta.meta_value = 'Legal Services' and wpostmeta.meta_value = 'New Brunswick'.
My guess is that this is what you want in the WHERE clause of the subquery -- change one of the ANDs to an OR:
....
WHERE (
(wpostmeta.meta_key = 'ulnooweg_business_industry'
AND wpostmeta.meta_value = 'Legal Services')
OR ( -- changed to an OR
wpostmeta.meta_key = 'ulnooweg_business_province'
AND wpostmeta.meta_value = 'New Brunswick')
)
....
The problem is in the where clause of your inner select; I'm guessing wpostmeta returns MULTIPLE rows. A previous comment that a string can't be two values is correct. The 2nd approach should work if the 1st doesn't
at first I thought
WHERE
((wpostmeta.meta_key = 'ulnooweg_business_industry' AND wpostmeta.meta_value = 'Legal Services') OR
(wpostmeta.meta_key = 'ulnooweg_business_province' AND wpostmeta.meta_value = 'New Brunswick'))
Group by Post_ID
HAVING count(post_ID) = 2
This will work ONLY if there is only one record in the wpostmeta for each type of entry. If
postmeta.meta_key = 'ulnooweg_business_industry' AND wpostmeta.meta_value = 'Legal Services' can occur twice, then the above does't work.
2nd approach
Select wposts.*
FROM WP_Posts wposts
INNER JOIN (
Select POST_ID from WP_POSTMeta where meta_key = 'ulnooweg_business_industry' AND wpostmeta.meta_value = 'Legal Services'
INTERSECT
SELECT POST_ID FROM WP_POST_META WHERE meta_key = 'ulnooweg_business_province' AND wpostmeta.meta_value = 'New Brunswick'
)
AS T on T.Post_ID = wposts.ID
I have a query which I have found on Sopocosy sport feed documentation. I have change this query to meet my need. Here is my query
SELECT
e.id as eid,
ts.name AS stage_name,
DATE_FORMAT(e.startdate, '%d.%m.%Y') AS startdate,
DATE_FORMAT(e.startdate, '%H:%i') AS starttime,
MIN(IF( ep.number = 1, p.name, NULL)) AS home_team,
IF(e.status_type = 'notstarted', '-',(MIN(IF(ep.number = 1, r.value, NULL)))) AS home_score,
IF(e.status_type = 'notstarted', '-',(MIN(IF(ep.number = 2, r.value, NULL)))) AS away_score,
MIN(IF(ep.number = 2, p.name, NULL)) AS away_team,
es.name AS status_text
FROM
tournament_template AS tt INNER JOIN
tournament AS t ON t.tournament_templateFK = tt.id INNER JOIN
tournament_stage AS ts ON t.id = ts.tournamentFK INNER JOIN
event AS e ON ts.id = e.tournament_stageFK INNER JOIN
event_participants AS ep ON e.id = ep.eventFK LEFT JOIN
status_desc AS es ON e.status_descFK = es.id LEFT JOIN
participant AS p ON ep.participantFK = p.id LEFT JOIN
result AS r ON ep.id = r.event_participantsFK AND r.result_code = 'runningscore' LEFT JOIN
property AS prop ON e.id = prop.objectFK AND prop.object ='event' AND prop.name = 'Live'
WHERE
tt.sportFK = '1'
GROUP BY
e.id
ORDER BY
ts.id, e.startdate, e.id
Now my question is
Can I use home_team and away_team in where clause. If yes then how. Like theoretically I want this in where clause.
WHERE home_team = 'Navibank Saigon' OR away_team = 'Navibank Saigon' ;
But it is giving Unknown Column error.
Please Help
Looks like p.name is the true column name of what is being returned as home_team so make your WHERE clause like
WHERE p.name = 'Navibank Saigon'
The reason why you can't use WHERE home_team = 'Navibank Saigon' OR away_team = 'Navibank Saigon' is that you assign these 'column names' (alias) on the result set after the search query is executed. The WHERE statement is part of the search query and needs the real column name, in this case p.name. On the other hand the ORDER BY statement is executed on the resultset and can thus use the column aliases like 'home_team'.
For the query part: you're using both teams in an aggregate function (MIN) on a GROUP BY statement. Filtering on a GROUP BY statement has to be done with HAVING instead of WHERE.
this results in:
GROUP BY
e.id
HAVING
MIN(IF( ep.number = 1, p.name, NULL)) = 'Navibank Saigon'
OR MIN(IF( ep.number = 1, p.name, NULL)) = 'Navibank Saigon'