Determine column data with if condition in a joined tables SQL - mysql

I have a query that works well, where i would like an assistance is how to incorporate a condition to determine the value displayed on a given column. That is if a column of a table has a value say "Authorization of COA" then the column date added should show the date else the column should show null
Here is my query so far
SELECT r.request_id, r.product_name, r.created_at, r.can,a_s.stat, r.client_id, CONCAT(u.fname,' ',u.lname) 'analyst' , t.date_added (//should show the value of date_added else NULL based on a condition for this column),
FROM request r
LEFT OUTER JOIN assigned_samples a_s ON r.request_id = a_s.labref
LEFT OUTER JOIN user u ON a_s.analyst_id = u.id
LEFT OUTER JOIN tracking_table t ON r.request_id = t.labref
WHERE r.client_id='$cid'
AND r.created_at BETWEEN '$start' AND '$end'
AND a_s.department_id = '$dept'
GROUP BY r.request_id
ORDER BY `r`.`created_at` DESC "

A simple CASE statement should be sufficient in this case, I believe.
SELECT r.request_id, r.product_name, r.created_at, r.can,a_s.stat, r.client_id,
CONCAT(u.fname,' ',u.lname) 'analyst',
CASE WHEN ConditionColumn = 'Authorization of COA' THEN t.date_added
ELSE NULL END AS 'date_added'
FROM request r
LEFT OUTER JOIN assigned_samples a_s ON r.request_id = a_s.labref
LEFT OUTER JOIN user u ON a_s.analyst_id = u.id
LEFT OUTER JOIN tracking_table t ON r.request_id = t.labref
WHERE r.client_id='$cid'

In both mysql and ms sql you can use case expression (mysql case; ms sql case) to assign value to a field conditionally:
SELECT r.request_id, r.product_name, r.created_at, r.can,a_s.stat, r.client_id, CONCAT(u.fname,' ',u.lname) 'analyst' ,
CASE WHEN Column_To_Test = 'Authorization of COA' THEN t.date_added
ELSE null
END AS date_added
FROM request r
LEFT OUTER JOIN assigned_samples a_s ON r.request_id = a_s.labref
LEFT OUTER JOIN user u ON a_s.analyst_id = u.id
LEFT OUTER JOIN tracking_table t ON r.request_id = t.labref
WHERE r.client_id='$cid'
AND r.created_at BETWEEN '$start' AND '$end'
AND a_s.department_id = '$dept'
GROUP BY r.request_id
ORDER BY `r`.`created_at` DESC "
This way the solution is more portable between the databases. Mysql offers if() function, ms sql iif() to achieve the above, but those are product specific solutions.

Try to use the Case statements like.
CASE WHEN ( Condition_1 AND Condition_2 OR ... Condition_N) THEN (Value_1) ELSE (Value_1) END
Here Condition_1 can be column record value and its combination of Column record values
and Value_1 can be single value [Ex: Null or "some string"] or Returned value from nested sql statement like [Ex: (select count(*) from ...)]

Give this a try:
SELECT r.request_id, r.product_name, r.created_at, r.can,a_s.stat, r.client_id, CONCAT(u.fname,' ',u.lname) 'analyst' ,
IFF(nameOfColumnToTest = 'Authorization of COA', t.date_added, null) AS DateAdded
FROM request r
LEFT OUTER JOIN assigned_samples a_s ON r.request_id = a_s.labref
LEFT OUTER JOIN user u ON a_s.analyst_id = u.id
LEFT OUTER JOIN tracking_table t ON r.request_id = t.labref
WHERE r.client_id='$cid'
AND r.created_at BETWEEN '$start' AND '$end'
AND a_s.department_id = '$dept'
GROUP BY r.request_id
ORDER BY `r`.`created_at` DESC "

Related

How to show the repeated value as NULL in sql?

I have a query which gives result as below, how to replace duplicate values with NULL
Query:
SELECT
word.lemma,
synset.definition,
synset.pos,
sampletable.sample
FROM
word
LEFT JOIN
sense ON word.wordid = sense.wordid
LEFT JOIN
synset ON sense.synsetid = synset.synsetid
LEFT JOIN
sampletable ON synset.synsetid = sampletable.synsetid
WHERE
word.lemma = 'good'
Result:
Required Result: all the greyed out results as NULL
First, this is the type of transformation that is generally better done at the application level. The reason is that it presupposes that the result set is in a particular order -- and you seem to be assuming this even with no order by clause.
Second, it is often simpler in the application.
However, in MySQL 8+, it is not that hard. You can do:
SELECT w.lemma,
(CASE WHEN ROW_NUMBER() OVER (PARTITION BY w.lemma, ss.definition ORDER BY st.sample) = 1
THEN ss.definition
END) as definition,
ss.pos,
st.sample
FROM word w LEFT JOIN
sense s
ON w.wordid = s.wordid LEFT JOIN
synset ss
ON s.synsetid = ss.synsetid LEFT JOIN
sampletable st
ON ss.synsetid = st.synsetid
WHERE w.lemma = 'good'
ORDER BY w.lemma, ss.definition, st.sample;
For this to work reliably, the outer ORDER BY clause needs to be compatible with the ORDER BY for the window function.
If you are using Mysql 8 try with Rank().. As I didn't have your table or data couldn't test this query.
SELECT
word.lemma
,case when r = 1 synset.definition else null end as definition
,synset.pos
,sampletable.sample
FROM
(
SELECT
word.lemma
,synset.definition
,synset.pos
,sampletable.sample
,RANK() OVER (PARTITION BY synset.definition ORDER BY synset.definition) r
FROM
(
SELECT
word.lemma,
synset.definition,
synset.pos,
sampletable.sample
FROM
word
LEFT JOIN
sense ON word.wordid = sense.wordid
LEFT JOIN
synset ON sense.synsetid = synset.synsetid
LEFT JOIN
sampletable ON synset.synsetid = sampletable.synsetid
WHERE
word.lemma = 'good'
) t
)t1;

MySQL LEFT JOIN ignores AND criteria

I have a functional LEFT JOIN MySQL query structured like this:
SELECT
COUNT(HTG_ScheduleRequest.ID) AS current_job,
HTG_TechProps.EmpNumber,
HTG_TechProps.EmpFirstName,
HTG_TechProps.EmpLastName,
HTG_TechProps.Veh_Number
FROM HTG_TechProps
LEFT JOIN HTG_ScheduleRequest ON HTG_TechProps.EmpNumber = HTG_ScheduleRequest.SSR
AND (HTG_ScheduleRequest.ScheduleDateCurrent = CURDATE() || HTG_ScheduleRequest.ScheduleDateExact = CURDATE())
AND RecordType = '1'
AND HTG_ScheduleRequest.JobStatus IN (2,5,8,3,4,7)
GROUP BY HTG_TechProps.EmpNumber ORDER BY HTG_TechProps.EmpNumber ASC
I need to add some criteria to the initial SELECT table like this:
HTG_TechProps.EmpStatus='A'
I get a Syntax error when I add a WHERE statement prior to the LEFT JOIN and when I add an AND like this after the LEFT JOIN it is ignored an still returning records that are not equal to A.
LEFT JOIN HTG_ScheduleRequest ON HTG_TechProps.EmpNumber = HTG_ScheduleRequest.SSR
AND HTG_TechProps.EmpStatus='A'
Conditions on the first table in a LEFT JOIN should go in a WHERE clause:
SELECT COUNT(sr.ID) AS current_job,
tp.EmpNumber, tp.EmpFirstName, tp.EmpLastName, tp.Veh_Number
FROM HTG_TechProps tp LEFT JOIN
HTG_ScheduleRequest sr
ON tp.EmpNumber = sr.SSR AND
(sr.ScheduleDateCurrent = CURDATE() OR sr.ScheduleDateExact = CURDATE()
) AND
sr.RecordType = '1' AND -- assume this comes from SR
sr.JobStatus IN (2, 5, 8, 3, 4, 7)
WHERE tp.EmpStatus='A'
GROUP BY tp.EmpNumber -- this is okay assuming that it is unique or (equivalently) a primary key
ORDER BY tp.EmpNumber ASC;
Note that this introduces table aliases so the query is easier to write and to read.
You should Use OR
SELECT
COUNT(HTG_ScheduleRequest.ID) AS current_job,
HTG_TechProps.EmpNumber,
HTG_TechProps.EmpFirstName,
HTG_TechProps.EmpLastName,
HTG_TechProps.Veh_Number
FROM HTG_TechProps
LEFT JOIN HTG_ScheduleRequest ON HTG_TechProps.EmpNumber = HTG_ScheduleRequest.SSR
AND (HTG_ScheduleRequest.ScheduleDateCurrent = CURDATE() OR HTG_ScheduleRequest.ScheduleDateExact = CURDATE())
AND RecordType = '1'
AND HTG_ScheduleRequest.JobStatus IN (2,5,8,3,4,7)
GROUP BY HTG_TechProps.EmpNumber
ORDER BY HTG_TechProps.EmpNumber ASC
and if you want apply where condtion for main table's columns you could use where eg:
SELECT
COUNT(HTG_ScheduleRequest.ID) AS current_job,
HTG_TechProps.EmpNumber,
HTG_TechProps.EmpFirstName,
HTG_TechProps.EmpLastName,
HTG_TechProps.Veh_Number
FROM HTG_TechProps
LEFT JOIN HTG_ScheduleRequest ON HTG_TechProps.EmpNumber = HTG_ScheduleRequest.SSR
AND HTG_ScheduleRequest.JobStatus IN (2,5,8,3,4,7)
WHERE (HTG_ScheduleRequest.ScheduleDateCurrent = CURDATE() OR HTG_ScheduleRequest.ScheduleDateExact = CURDATE())
AND HTG_TechProps.RecordType = '1'
GROUP BY HTG_TechProps.EmpNumber
ORDER BY HTG_TechProps.EmpNumber ASC

Unknown column where clause

I have following DQL query
SELECT
ps.id,
MAX(ps.dueDate) as due_date,
u.firstName as first_name,
u.lastName as last_name,
u.email,
IDENTITY(ps.loanApplication) as loan_application_id,
DATE_DIFF(MAX(ps.dueDate), CURRENT_DATE()) as diff
FROM
Loan\Entity\PaymentSchedule ps
LEFT JOIN
ps.paymentType pt
LEFT JOIN
ps.loanApplication la
LEFT JOIN
la.status s
LEFT JOIN
la.user u
WHERE
pt.slug != :paymentSlug AND s.keyIdentifier = :status AND diff = 14
GROUP BY
ps.loanApplication
Which translates to following SQL query
SELECT
p0_.id AS id_0,
MAX(p0_.due_date) AS sclr_1,
u1_.first_name AS first_name_2,
u1_.last_name AS last_name_3,
u1_.email AS email_4,
p0_.loan_application_id AS sclr_5,
DATEDIFF(MAX(p0_.due_date), CURRENT_DATE) AS sclr_6
FROM
payment_schedule p0_
LEFT JOIN
payment_type p2_ ON p0_.payment_type_id = p2_.id
LEFT JOIN
loan_application l3_ ON p0_.loan_application_id = l3_.id
LEFT JOIN
loan_application_status l4_ ON l3_.loan_application_status_id = l4_.id
LEFT JOIN
user u1_ ON l3_.user_id = u1_.id
WHERE
p2_.slug <> ? AND l4_.key_identifier = ? AND sclr_6 = 14
GROUP BY
p0_.loan_application_id
This gives me following error
======================================================================
PDOException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sclr_6' in 'where clause'
----------------------------------------------------------------------
When i replace WHERE condition
WHERE pt.slug != :paymentSlug AND s.keyIdentifier = :status AND diff = 14
With
WHERE pt.slug != :paymentSlug AND s.keyIdentifier = :status
It works perfectly and displays me correct record, i also tried following WHERE condition
WHERE pt.slug != :paymentSlug AND s.keyIdentifier = :status AND DATE_DIFF(MAX(ps.dueDate), CURRENT_DATE()) = :days_diff
WHERE pt.slug != :paymentSlug AND s.keyIdentifier = :status HAVING (DATE_DIFF(MAX(ps.dueDate), CURRENT_DATE())) = :days_diff
Above WHERE does not work as well, what am i missing here ?
Thanks.
If you want to use the alias in your WHERE clause you need a sub-select.
select *
from
(SELECT
p0_.id AS id_0,
MAX(p0_.due_date) AS sclr_1,
u1_.first_name AS first_name_2,
u1_.last_name AS last_name_3,
u1_.email AS email_4,
p0_.loan_application_id AS sclr_5,
DATEDIFF(MAX(p0_.due_date), CURRENT_DATE) AS sclr_6
FROM
payment_schedule p0_
LEFT JOIN
payment_type p2_ ON p0_.payment_type_id = p2_.id
LEFT JOIN
loan_application l3_ ON p0_.loan_application_id = l3_.id
LEFT JOIN
loan_application_status l4_ ON l3_.loan_application_status_id = l4_.id
LEFT JOIN
user u1_ ON l3_.user_id = u1_.id
) A
WHERE
slug <> ? AND key_identifier = ? AND sclr_6 = 14
This is how query is logically processed
FROM clause
WHERE clause
SELECT clause
GROUP BY clause
HAVING clause
ORDER BY clause
Since Where comes before Select you cannot use alias name in Where clause
You cannot use an alias (on the final result fields) in the WHERE clause; however, at least with MySQL, you may use a HAVING clause without needing a GROUP BY.
The expression you are using is the result of an aggregation. Replace add a having clause so the query looks like;
SELECT . . .
WHERE p2_.slug <> ? AND l4_.key_identifier = ?
GROUP BY p0_.loan_application_id
HAVING sclr_6 = 14
Note that date_diff() is not a function in MySQL. You intend datediff().

ordering 2 tables by date

I want to order 2 tables by date, but the problem is sql is not ordering them simultaneously.
here is my query:
SELECT users_id,CONCAT_WS(' ', users_fname, users_lname)
AS full_name, reply_message, concern_message
FROM tbl_usersinfo AS i
LEFT JOIN tbl_concern AS c
ON c.student_id = i.users_id
LEFT JOIN tbl_reply_concern AS r
ON r.student_id = i.users_id
ORDER BY c.date,r.date
I read that i need to put ISNULL(c.date,r.date) but its not working.
Try ifnull or coalesce
SELECT users_id,
CONCAT_WS(' ', users_fname, users_lname) AS full_name,
reply_message,
concern_message
FROM tbl_usersinfo AS i
LEFT JOIN tbl_concern AS c
ON c.student_id = i.users_id
LEFT JOIN tbl_reply_concern AS r
ON r.student_id = i.users_id
ORDER BY ifnull(c.date, r.date)
The MySQL equivalent of ISNULL (in SQL Server) is IFNULL. In MySQL I believe ISNULL is just a test of whether something is or is not null which would evaluate to 0 or 1.

SQL Query Problem

I've been at this for a bit now. Basically, I'm needing to add a derived column to count the hits to a weblog entry in the database. The problem is, the hits are being totaled and shown on only on the first record. Any Ideas? I've emboldened the parts of the query I'm talking about. The query is below:
SELECT DISTINCT(t.entry_id),
exp_categories.rank,
**exp_hits.hits,**
t.entry_id,
t.weblog_id,
t.forum_topic_id,
t.author_id,
t.ip_address,
t.title,
t.url_title,
t.status,
t.dst_enabled,
t.view_count_one,
t.view_count_two,
t.view_count_three,
t.view_count_four,
t.allow_comments,
t.comment_expiration_date,
t.allow_trackbacks,
t.sticky,
t.entry_date,
t.year,
t.month,
t.day,
t.entry_date,
t.edit_date,
t.expiration_date,
t.recent_comment_date,
t.comment_total,
t.trackback_total,
t.sent_trackbacks,
t.recent_trackback_date,
t.site_id as entry_site_id,
w.blog_title,
w.blog_name,
w.search_results_url,
w.search_excerpt,
w.blog_url,
w.comment_url,
w.tb_return_url,
w.comment_moderate,
w.weblog_html_formatting,
w.weblog_allow_img_urls,
w.weblog_auto_link_urls,
w.enable_trackbacks,
w.trackback_use_url_title,
w.trackback_field,
w.trackback_use_captcha,
w.trackback_system_enabled,
m.username,
m.email,
m.url,
m.screen_name,
m.location,
m.occupation,
m.interests,
m.aol_im,
m.yahoo_im,
m.msn_im,
m.icq,
m.signature,
m.sig_img_filename,
m.sig_img_width,
m.sig_img_height,
m.avatar_filename,
m.avatar_width,
m.avatar_height,
m.photo_filename,
m.photo_width,
m.photo_height,
m.group_id,
m.member_id,
m.bday_d,
m.bday_m,
m.bday_y,
m.bio,
md.*,
wd.*
FROM exp_weblog_titles AS t
LEFT JOIN exp_weblogs AS w ON t.weblog_id = w.weblog_id
LEFT JOIN exp_weblog_data AS wd ON t.entry_id = wd.entry_id
LEFT JOIN exp_members AS m ON m.member_id = t.author_id
LEFT JOIN exp_member_data AS md ON md.member_id = m.member_id
LEFT JOIN exp_category_posts ON wd.entry_id = exp_category_posts.entry_id
**LEFT JOIN
(
SELECT COUNT(*) AS hits, exp_hits.entry_id FROM exp_hits ORDER BY exp_hits.entry_id
) exp_hits ON t.entry_id = exp_hits.entry_id**
LEFT JOIN
(
SELECT exp_categories.cat_id, cat_name as rank
FROM exp_categories
WHERE exp_categories.group_id = '9'
) exp_categories ON exp_categories.cat_id = exp_category_posts.cat_id
WHERE t.entry_id IN (2,3,4) ORDER BY exp_categories.rank DESC, **exp_hits.hits DESC**, entry_date desc
Try changeing the subselect to
SELECT COUNT(*) AS hits,
exp_hits.entry_id
FROM exp_hits
GROUP BY exp_hits.entry_id
Out of curiosity, is your hits functionality something that can't be accomplished with the view_count_one/two/three/four fields already present in the database and supported by ExpressionEngine template tags?