MySQL Return the first non-NULL value from the list of the column in select statement with column name - mysql

I have a sql query below:
SELECT
md.refereeInternetSearch,
md.refereeCompanyColleague,
md.refereeIndustryPeer,
md.refereeIndustryEvent,
md.refereeIndustryPublication,
md.refereeMarketingEmail,
md.refereeOther
FROM
marketing_details md
WHERE
md.id = 14588
From the 7 columns in the above select statement only one column will have a value and rest will be null. Is it possible to select just that one column value that is not null using some sort of sql statement ?

Use the coalesce() function to return the 1st non-null value from a list of parameters:
SELECT
coalesce(md.refereeInternetSearch,
md.refereeCompanyColleague,
md.refereeIndustryPeer,
md.refereeIndustryEvent,
md.refereeIndustryPublication,
md.refereeMarketingEmail,
md.refereeOther) as non_null_value
FROM
marketing_details md
WHERE
md.id = 14588
However, it will not be able to tell you which column the value came from.
UPDATE
If you really want to use sql to retrieve the name of the field that has the non null value, then you can do that with the following monstrous sql statement below. What it does it concatenates each field value from a record into a single string, where the values are separated by comma. NULL values are converted to empty string. Then using find_in_set() function it finds the position of the only non null value within the above string. Then using the elt() function it returns the name of the field from the list of field name literals based on the position returned by find_in_set().
SELECT
md.id,
coalesce(md.refereeInternetSearch,
md.refereeCompanyColleague,
md.refereeIndustryPeer,
md.refereeIndustryEvent,
md.refereeIndustryPublication,
md.refereeMarketingEmail,
md.refereeOther) as non_null_value,
elt(find_in_set(coalesce(md.refereeInternetSearch,
md.refereeCompanyColleague,
md.refereeIndustryPeer,
md.refereeIndustryEvent,
md.refereeIndustryPublication,
md.refereeMarketingEmail,
md.refereeOther),
concat(coalesce(md.refereeInternetSearch,''),',',
coalesce(md.refereeCompanyColleague,''),',',
coalesce(md.refereeIndustryPeer,''),',',
coalesce(md.refereeIndustryEvent,''),',',
coalesce(md.refereeIndustryPublication,''),',',
coalesce(md.refereeMarketingEmail,''),',',
coalesce(md.refereeOther,'')
)
),'refereeInternetSearch',
'refereeCompanyColleague',
'refereeIndustryPeer',
'refereeIndustryEvent',
'refereeIndustryPublication',
'refereeMarketingEmail',
'refereeOther'
) as field_name
FROM
marketing_details md
WHERE
md.id = 14588
Huh, I hope I got all the parentheses right!

Related

SQL sum select returns null

I want to obtain unread messages count from MySQL database using SELECT SUM operator.
So, my SQL is:
SELECT sum(status_field = 'new') unreadMessagesCount
FROM messages
WHERE 'author_uid' = 'authorUID'
And it returns NULL. Why?
I have items in database and I can select it by (SELECT * FROM messages)
It returns NULL because you are comparing strings, not columns with:
WHERE 'author_uid' = 'authorUID'
And these two strings are not equal. So, all rows are filtered out. The NULL value is because you have an aggregation query. SUM() returns NULL when there are no rows in such a query.
I'm not sure what you intend. Perhaps:
WHERE author_uid = 'authorUID'
However, 'authorUID' seems like a strange value for a uid. You need to put an appropriate value there. If it is a string, enclose it in single quotes. If it is a number, do not use single quotes.

Replace null with zero in sql query

I have an sql query that could potentially return null values, in the event of this I want the query to return '0'. Here is the query
SELECT (select count(goal) from fixtures where goal='1' and fixture='$fixture') as goalCountHome
from fixtures where fixture='$fixture'LIMIT 1
Any help much appreciated!
In MySql use IFNULL() function. For MsSql use ISNULL() function.
If you are using MySql, IFNULL(<column_name>, 0) should do.
This query:
SELECT (select count(goal) from fixtures where goal='1' and fixture='$fixture') as goalCountHome
FROM fixtures
WHERE fixture = '$fixture'
LIMIT 1
cannot return NULL values. The subquery is an aggregation query with no GROUP BY, so it always returns one row. That row will contain a result from COUNT(). COUNT() itself can never return a NULL value. If there are no rows, then the value will be zero.
The outer query might return no rows but that is different from NULL values.
Of course, this query is way overcomplicated, and should simply be:
SELECT COUNT(*) as goalCountHome
FROM fixtures
WHERE fixture = ? AND -- pass this in as a parameter
goal = 1 ; -- it looks like a number so I assume it is
Note that you should be passing parameters in using proper parameters rather than munging query strings.
if you need all the rows and not the rows where goal is not null you could use count(*)
select count(*)
from fixtures
where goal=1
and fixture='$fixture'
count(goal) return the number of rows where goal is not null
count(*) return the total number rows selected
otherwise in general when you need not null values in mysql you can ifnull(your_column, value) or coalesce(your_column, value)
based on you comment seems you need sum(goal)
select sum(ifnull(goal,0))
from fixtures
where goal=1
and fixture='$fixture'

The Value expression for the textrun ‘Textbox15.Paragraphs[0].TextRuns[0]’ contains an error: [BC30201] Expression expected

I received this error when I am trying to run a select statement in a text box in SSRS. So, basically, I am trying to return a field which is not in the given dataset. So I have run a subquery which returns the value using the existing dataset as a container.
But I don't know how to represent that return value in the Expression field. Because the expression field returns a value which is within the dataset provided.
I have provided the SQL that I have written.
Any suggestions would be much appreciated.
My intention is to return the "CommentText" value. However, the dataset does not contain any commenttext field, but an EmpID field. So I have created the subquery below that brings up the CommentText from LaborDtlComment table and when it matches with the EmpID in the report dataset it returns the CommentText Value.
select [CommentReturnQuery].[LaborDtlComment_CommentText] as [LaborDtlComment_CommentText],
[EmpBasic].[EmpID] as [EmpBasic_EmpID]
from Erp.EmpBasic as EmpBasic
inner join (select [LaborDtlComment].[CommentText] as [LaborDtlComment_CommentText],
[LaborDtl].[EmployeeNum] as [LaborDtl_EmployeeNum]
from Erp.LaborDtlComment as LaborDtlComment
inner join Erp.LaborDtl as LaborDtl on LaborDtlComment.Company = LaborDtl.Company
and LaborDtlComment.LaborHedSeq = LaborDtl.LaborHedSeq
and LaborDtlComment.LaborDtlSeq = LaborDtl.LaborDtlSeq) as CommentReturnQuery
on EmpBasic.EmpID = CommentReturnQuery.LaborDtl_EmployeeNum
My aim is to show the CommentText value in a text field. So I will create the
text field and it will contain the SQL that I have written. Can anyone help
me in this case?
It maybe simpler to use the SSRS function lookup (single paired 1 to 1) or lookupset (multiple 1 to many).microsoft lookup reference
You will have to create the query/dataset to return CommentText from LaborDtlComment table with the EmpID

Attempting to pull concatenated Q-urls, using data-type in a table

Will try and explain as concisely as I can.
Below is a dummy query based on one I'm attempting to edit.
I'm trying to return two different types which are pulled from the same table.
The first type of data is a numeric (a score from 1-10)
The next type of data is a both numbers and letters, used to complete a URL.
My problem is that the concat statement to return only null values. when I use the and statement to specify only URL data, the other column returns only null values.
Is there a way I can change this, to pull only one type of data in one column separate to the other?
Cheers
select
concat("example.com/",rs.answer,"/415x380.png") as Q_URL,
Ease_of_use.score as "Ease_Of_use"
from customer_feedback c
left join response_data Ease_of_use on (Ease_of_booking_use.response_overall_id=c.id and Ease_of_use.data_type_id=1536)
left join response_data rs on rs.customer_review_id=c.id
join data_type dt on dt.id=rs.data_type_id
where c.retailer_id in (678,1651)
and rs.answer is not null
and dt.response_type="photo_URL"
group by c.id
I'm not sure what you mean by "I use the and statement to specify only URL data", but I would use isnull function to provide a default value for NULLS
concat("example.com/",isnull(rs.answer,"default value"),"/415x380.png")
rather than using rs.answer is not null

Tablix Filter for Including NULL in SSRS

I have an SSRS report. It has a Marks dropdown, and a resultset "Classresult". When I select any value from Marks dropdown, it filters my result for selected value and displays the result.
Say when I select "100" from marks dropdown, it filters my Classresult dataset and shows all results with 100 value.
But it doesnot show values which have NULL in marks field.(the resultset ClassResult contains NULL values.
Is there any way i can include NULL values ??
Currently my condition is:
Marks == Parameters!Marks.Value
Do you have the ability to wrap an IsNull() around the Class result field in your datasource?
Like IsNull(ClassResult,0) AS Classresult
This will replace nulls with a zero. Alternately you could replace the 0 with a different value of your choice.
Use the IsNothing() function to check for a NULL value in an SSRS expression. It returns TRUE if the value is NULL.
You can include NULL in the query that populates the Marks drop down. (If you put the available values in statically, then add it there...) but here is how you can do it in the query.
SELECT ValueField, LabelField
FROM MarksTable
UNION
SELECT '(NULL)', '--NULL--'
Then in the query whose results you are filtering add
ISNULL([Marks], '(NULL)') as Marks