MySQL count (and sum) fields in multiple columns where 'not empty' - mysql

I'm using this MySQL query
SELECT COUNT(pros_a) + COUNT(pros_b) + COUNT(pros_c) + COUNT(pros_d) + COUNT(pros_e) AS pros_total FROM my_table WHERE contentid = 'id'
to count and sum fields in each column. But this returns ALL fields (full and empty). I want to count only filled fields, excluding empty fields. How can I do that? Just a little bit... confused! :)
Any help would be very appreciated!
Thanks
EDIT:
my_table
pros_a pros_b pros_c pros_d pros_e
------- ------ ------ ------ ------
good (empty) good good (empty)
expected result
pros_total
----------
3

The COUNT(column) function does not count fields that are NULL. It counts empty (zero-length) strings though.
You can change these into:
COUNT( CASE WHEN column <> '' THEN column END )
or:
SUM(column <> '')
The last works in MySQL because TRUE is evaluated as 1 and FALSE as 0.

SELECT COUNT(DISTINCT pros_a) + COUNT(DISTINCT pros_b) + COUNT(DISTINCT pros_c) + COUNT(DISTINCT pros_d) + COUNT(DISTINCT pros_e) FROM my_table WHERE contentid = 'id'
The above one should work.

Use where condition for empty fields, for example WHERE pros_a != '' or pros_a != '0' if is NULL. pros_a != '' AND pros_b != ''

Related

match a number using regex for comma separated number

I have a string that contains number with separated by comma like below.
15,22,20,26,33,445,40,44,22,225,115,2
I want to know if a number say 15 is in that string or not.The problem is that 15 and 115 both are a match.Same for other number say 2, for this case 20 , 25, and 225 are match.For both cases only it should return if there is 15 or 2 in the string.I tried using like keyword but it's not working. It also return the rows with 115 or 20, 225, 222 whille matching 15 and 2 respectively. Can anyone suggest a regex pattern?
Update
I have a query like below where I was using like keyword, but I was getting wrong result for above reason.
SELECT DISTINCT A.id,A.title,A.title_hi,A.cId,B.id as cid1,A.report_type ,A.icon_img_url, A.created_at , A.news_date
FROM tfs_report_news A, tfs_commodity_master B
WHERE (',' + RTRIM(A.cId) + ',') LIKE ('%,' + B.id + ',%')
AND A.ccId = B.ccId AND A.`report_type`= "M"
AND A.isDeleted=0 AND A.isActive=1 AND B.isDeleted=0
AND B.status=1
AND A.news_date= (SELECT MAX(T.news_date)
FROM tfs_report_news T WHERE (',' + RTRIM(T.cId) + ',')
LIKE ('%,' + B.id + ',%'))
ORDER BY created_at desc, id desc limit 100;
Here tfs_report_news has the string 15,22,20,26,33,445,40,44,22,225,115,2 as column name cId and individual cId like 15 or 2 is id of tfs_commodity_master
In MySQL, what you asked for is the purpose of string function find_in_set():
Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings. A string list is a string composed of substrings separated by , characters [...] Returns 0 if str is not in strlist or if strlist is the empty string. Returns NULL if either argument is NULL.
So to check if a value is present in the list, you can just do:
find_in_set('15', '15,22,20,26,33,445,40,44,22,225,115,2') > 0
Side note: here is a recommended reading.
Use FIND_IN_SET:
SELECT
CASE WHEN FIND_IN_SET('15', csv) > 0 THEN 'yes' ELSE 'no' END AS result
FROM yourTable;
Another option would be to use LIKE:
SELECT
CASE WHEN CONCAT(',', csv, ',') LIKE '%,15,%' THEN 'yes' ELSE 'no' END AS result
FROM yourTable;
Finally, you could also use REGEXP here:
SELECT
CASE WHEN csv REGEXP '[[:<:]]15[[:>:]]' THEN 'yes' ELSE 'no' END AS result
FROM yourTable;

MysQL Update if a count condition is met

I have a table which consists of 5000 rows. I need SQL command that could update each row by removing all values in "(...)" if only one couple of () is found.
Basically, if I have a name in a row:
Name surname (extra info)
I need to remove "(extra info)" and leave only Name surname
But if there is no additional couple of ()
If there is a row
Name Surname(data) (extra info)
The script should not amend this name
In simple words, I need to update a name where is only one ( or ) symbol
Many thanks
can you try to find first '(' and substring to it ?
don't forget to use case for none ( in string
update userlogin
set fullname = case position('(' in FullName)
when 0
then fullname
else substring(Fullname,1,position('(' in FullName) - 1)
end
This is an implementation of my question. I used select to let me check the result before applying it to update request. The script shows a table of
3 columns: Id, Name, UpdatedName, where Name is what we have and UpdatedName what we will obtain
SELECT `Id`,`Name`,
(case when ((LENGTH(`Name`)-LENGTH(REPLACE(`Name`, '(', ''))) = 1)
THEN
SUBSTRING_INDEX(`Name`, '(', 1)
ELSE
'-'
END)
as updated_name,
FROM table
WHERE (LENGTH(`Name`)-LENGTH(REPLACE(`Name`, '(', ''))) = 1
LIMIT 0,1500
P.S. I used Id to allow me to amend values
SELECT CASE
WHEN fname = 'correct' THEN 'your condition'
WHEN sname = 'correct' THEN 'your second condition'
ELSE 'baz'
END AS fullname
FROM `databasetable`
or you can do as like also
CASE
WHEN action = 'update' THEN
UPDATE sometable SET column = value WHERE condition;
WHEN action = 'create' THEN
INSERT INTO sometable (column) VALUES (value);
END CASE

MySQL issue with NULL values

I have a table with fields: country_code, short_name, currency_unit, a2010, a2011, a2012, a2013, a2014, a2015. a2010-a2015 fields are type of double.
How do I make a query which orders the results by average of fields a2010-a2015, keeping in mind that these fields might have NULL value?
I tried this code and it did not work (returns a mistake, which tells there is something wrong in ORDER BY part. mistake was saying something about coumn names and GROUP BY). The logic is: ORDER BY ((A)/(B)) where A - sum of not NULL fields and B - count of not NULL fields.
Any ideas?
(if important, the code is going to be used in BigInsights environment)
SELECT country_code, short_name, currency_unit, a2010, a2011, a2012,
a2013, a2014, a2015
FROM my_schema.my_table
WHERE Indicator_Code = 'SE.PRM.TENR'
ORDER BY
(
(
Coalesce(a2010,0) + Coalesce(a2011,0) + Coalesce(a2012,0)
+Coalesce(a2013,0) + Coalesce(a2014,0) + Coalesce(a2015,0)
)
/
(
COUNT(Coalesce(a2010)) + COUNT(Coalesce(a2011)) + COUNT(Coalesce(a2012))
+ COUNT(Coalesce(a2013)) + COUNT(Coalesce(a2014)) +
COUNT(Coalesce(a2015))
)
) DESC;
use MySQL ifnull
IFNULL(expression_1,expression_2)
in your query :-
IFNULL(
(
COUNT(Coalesce(a2010)) + COUNT(Coalesce(a2011)) + COUNT(Coalesce(a2012))
+ COUNT(Coalesce(a2013)) + COUNT(Coalesce(a2014)) +
COUNT(Coalesce(a2015))
),
1
)

Count flags for a variable (big) number of colums

I have a table which looks like this: http://i.stack.imgur.com/EyKt3.png
And I want a result like this:
Conditon COL
ted1 4
ted2 1
ted3 2
I.e., the count of the number of '1' only in this case.
I want to know the total no. of 1's only (check the table), neglecting the 0's. It's like if the condition is true (1) then count +1.
Also consider: what if there are many columns? I want to avoid typing expressions for every single one, like in this case ted1 to ted80.
Using proc means is the most efficient method:
proc means data=have noprint;
var ted:; *captures anything that starts with Ted;
output out=want sum =;
run;
proc print data=want;
run;
Try this
select
sum(case when ted1=1 then 1 else 0 end) as ted1,
sum(case when ted2=1 then 1 else 0 end) as ted2,
sum(case when ted3=1 then 1 else 0 end) as ted3
from table
In PostgreSQL (tested with version 9.4) you could unpivot with a VALUES expression in a LATERAL subquery. You'll need dynamic SQL.
This works for any table with any number of columns matching any pattern as long as selected columns are all numeric or all boolean. Only the value 1 (true) is counted.
Create this function once:
CREATE OR REPLACE FUNCTION f_tagcount(_tbl regclass, col_pattern text)
RETURNS TABLE (tag text, tag_ct bigint)
LANGUAGE plpgsql AS
$func$
BEGIN
RETURN QUERY EXECUTE (
SELECT
'SELECT l.tag, count(l.val::int = 1 OR NULL)
FROM ' || _tbl || ', LATERAL (VALUES '
|| string_agg( format('(%1$L, %1$I)', attname), ', ')
|| ') l(tag, val)
GROUP BY 1
ORDER BY 1'
FROM pg_catalog.pg_attribute
WHERE attrelid = _tbl
AND attname LIKE col_pattern
AND attnum > 0
AND NOT attisdropped
);
END
$func$;
Call:
SELECT * FROM f_tagcount('tbl', 'ted%');
Result:
tag | tag_ct
-----+-------
ted1 | 4
ted2 | 1
ted3 | 2
The 1st argument is a valid table name, possibly schema-qualified. Defense against SQL-injection is built into the data type regclass.
The 2nd argument is a LIKE pattern for the column names. Hence the wildcard %.
db<>fiddle here
Old sqlfiddle
Related:
Select columns with particular column names in PostgreSQL
SELECT DISTINCT on multiple columns

Can Sybase CASE expressions have a default column name for their result?

I have a sybase query that is structured like this:
SELECT
case
when isnull(a,'') <> '' then a
else convert(varchar(20), b)
end
FROM table_name
WHERE b=123
It used to return the results of the 'case' in a column named 'converted'. It now returns the results of the 'case' in a column with an empty string name ''.
How could this be? Could there be some database configuration that defaults the results of a 'case' with no name?
(I've fixed the broken query by adding " as computed" after 'end' but now I'd like to know how it used to return as 'computed' before I added the fix?)
Is this what you want?
SELECT (case when isnull(a, '') <> '' then a
else convert(varchar(20), b)
end) as converted
-------------^
FROM table_name
WHERE b = 123;
By the way, you could write the select more succinctly as:
SELECT coalesce(nullif(a, ''), b) as converted