Mysql SUM inside a CASE - mysql

Say I have a query that is something like this:
select
table1.column1,
table1.column2,
...,
case when foo.id is null then 'N/A' else sum(foo.points) end as score -- same result using ifnull()
from
table1 inner join table2 on ...
left join foo on ...
group by ...
Since I do a LEFT JOIN on foo, there is a chance that there is no match. In that case, I want the score to show as 'N/A' instead of NULL or 0. But when I do the above query, I get blob for the score column for all rows.

When you have different data types in the results in the case it will return a value with the data type blob if it can't find a common type.
Try casting the sum to a char:
case when foo.id is null then 'N/A' else cast(sum(foo.points) as char) end as score

If you are grouping, you should really put your sum around the case, like:
sum(case when foo.id is null then 0 else foo.points)
..as otherwise you are summing just the row value (meaning only one value).
Also, a column should only have one data type, so either number or text, which is why you might be seeing this issue since you are trying to display either a number or text in the same column.
If you really want N/A, you can try converting the number to text, and then using the coalesce function to handle nulls, however I would need to see your data to say the best way to write your above query. If you can create an SQL fiddle, I would be more than happy to take a look :)

SUM up the the results of the CASE..WHEN.
SUM(CASE WHEN foo.id IS NULL THEN NULL ELSE foo.points) END AS score
You can display the default value in the frontend application (n/a) when the score field is null (or equals to 0).
The score will be NULL when there all rows has null in foo.id.

Related

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'

SQL Select Max of Columns Where Date is Not Null

I currently am using this query to select some data:
SELECT DISTINCT a.code AS code, name, max(scen.Is3D) AS Is3D FROM locations LEFT JOIN .... The scen table has columns Is3D and Date. I only want to select the max of items where the date IS NOT NULL. I tried max(scen.Is3D WHERE scen.Date IS NOT NULL), but that didn't work. I cannot change anything after the FROM in my query, so I need that filtering to be done in the MAX, if possible. I am using MySQL 5.7.
You can use:
MAX(CASE WHEN scen.date IS NOT NULL THEN scen.Is3D END) AS Is3D
The CASE expression returns NULL when none of the WHEN conditions is met, but MAX() ignores null values, so this will just return the max of the Is3D columns in the selected rows.
So if we can't change anything after the FROM, then we cannot get a perfect solution here. Since you are SELECTing out the NULL values. One thing that we can try if we can only modify the final output is this.
SELECT MAX(ISNULL(scen.Date,0))...
This will replace all the NULLs with 0, but it would help to know exactly what you are trying to do. Why are you so convinced that the query itself cannot be modified in any way?
The other solution would be to put the whole query in another wrapper.
That would look like:
SELECT *
FROM (
[your whole query here]
) AS inner
WHERE inner.Date IS NOT NULL

COUNTNULL() as a MySQL function. How would it operate?

I am sure it would be an aggregate function because it is going to count a collection of data.
However, how does any COUNT() function operate in MySQL to perform its respective actions?
Not 100% clear what you are looking for, but for selecting a count of null values in a column, I use something like this:
SELECT SUM(CASE WHEN columnname IS NULL THEN 1 ELSE 0 END) FROM tablename;
When the value is NULL, it is assigned the value 1 otherwise 0, then summed over whatever aggregate you need.
The COUNT(*) is an aggregate function. In the SELECT list, the expression COUNT(*) will return a count of rows. Without a GROUP BY clause, all rows will be collapsed into a single row, and the COUNT(*) aggregate will contain a non-negative integer value representing the number of rows that were collapsed... a "count" of the number of rows.
As you seem to be aware, other expressions involving the COUNT() aggregate operate a little differently, with respect to NULL values.
In the SELECT list, an expression COUNT(expr) operates exactly like COUNT(*) except for rows with values of expr that evaluate to NULL are not included in the count.
This all operates according to the specification.
As far as the non-existent COUNTNULL() function, it depends what you want that to achieve. If you wanted to get a count of the rows that had a NULL value for an expression, you could perform a conditional test, and return a non-NULL value, and use the existing COUNT aggregate, for example:
SELECT COUNT(CASE WHEN expr IS NULL THEN 1 ELSE NULL END) AS `COUNTNULL`
FROM ...
I don't remember where I learned this technique, but arguably the most elegant -- or at least minimalistic -- way to invert the logic of COUNT() is with this expression, which admittedly gives a first impression that black magic may somehow be involved... but it's perfectly legitimate:
COUNT(column1 IS NULL OR NULL)
...this correctly counts only the rows where column1 is null, because it is equivalent to the following expression...
COUNT( (column1 IS NULL) OR (NULL) )
It's a boolean expression that can only ever evaluate to 1 ("true," when column1 is null, and this row is thus counted), or NULL (otherwise, so the row will not be counted).
Logically, it's equivalent to the CASE expression offered by #spencer7593.

When statment to replace Null data

money
20.00
17.87
5.00
NULL
3.00
I want the null entries turned into zeroes. The money column is for money spent. Ive tried the following and it didnt like changing NUll to a dollar value.
select case money when 'NULL' then 0 end
from mytable
select coalesce(money, 0) from mytable
Coalesce will take the first non-null value in the list.
Try:
SELECT IsNull(money, 0)
FROM mytable
EDIT
If you want to replace the values in the table:
UPDATE mytable
SET money = 0
WHERE money Is Null
While I agree with the other two answers, I wasnted to explain why what you did was not right.
select case money when 'NULL' then 0 end
from mytable
Here you are treating NULL as a string value. But NULL is a condition not a value. It means there is no known value. If you inserted the actual word 'null' into the table in that field, then your code would have worked.
When you want to test for a NULL condition you use:
WHERE field1 IS NULL
or you change the value using coalesce or ISNULL. If you need to test for NULL as part of a case statement, then you would do it like this:
CASE WHEN field1 IS NULL THEN 0 ELSE T1 END
For simple cases like yours, COALESCE or ISNULL is best. But at times you may need to do a very complicated CASE and then it is handy to know how to do it.

MySQL GROUP BY NULL and EMPTY

In a MySQL query I am doing a GROUP BY with a text field. Due to the nature of the original data, some rows are contain empty strings for this field, and others are true null.
When grouping, how can I group empty string and null together, treating both as null?
This can be accomplished by SELECT CASE. There may be a simpler way I do not know of.
The format of SELECT CASE is
SELECT
CASE
WHEN table_name.text_field IS NULL OR table_name.text_field = ''
THEN null
ELSE table.text_field
END as new_field_name,
other_field, another_field, ...rest of query...
So you see, you can CASE together values with WHEN/THEN and default to the real value by ELSE.