I'm creating a query wherein I would count how many awards does an applicant have. So far I have this:
SELECT
CASE WHEN Award1 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN Award2 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN Award3 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN Award4 IS NOT NULL THEN 1 ELSE 0 END
as summedColumn
FROM resume, person
where E_Status = 'Applicant'
and person.ID_No like 'x' and resume.ID_No like 'x'
Table:Person Values
ID_No(Varchar, Primary) x
F_Name(Varchar) Fasa
L_Name(Varchar) Bel
M_Name(Varchar) Drake
Resume_ID(Varchar) res01
Table: Resume Value
Resume_ID(Varchar, Primary) res01
ID_No(Varchar) x
Award1(Varchar) Suma Cum Laude
Award2(Varchar) null
Award3(Varchar) null
Award4(Varchar) null
Past_Position1(Varchar) HR manager
Past_Position2(Varchar) null
Output of the query: 4
When I ran the code it returned a value of 4 but my Award2, Award3 and Award4 are all null. The code suppose to return a value of 1.
Here is the look of the table:
You didn't join your two tables, so it is making a cross join between Resume and Person tables.
Find the key which relates Person to Resume, and equals them together:
SELECT
CASE WHEN Award1 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN Award2 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN Award3 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN Award4 IS NOT NULL THEN 1 ELSE 0 END
as summedColumn
FROM resume
INNER JOIN person
ON resume.Resume_ID = person.Resume_ID
where E_Status = 'Applicant'
and person.ID_No like 'x' and resume.ID_No like 'x'
Maybe you want to rethink your database structure.
How about creating an 1:n structure?
Table structure Person: ID, Name ...
Table Structure AwardRel: PersonID, AwardRel
Table Structure Awards: ID, AwardName, ...
With a 1:n structure like this, your query can be expressed as:
SELECT COUNT(*) FROM `AwardRel` WHERE `PersonID` = 1;
This query should return any number of awards Person 1 has ever obtained.
Related
I have table as data_attributes with a column data_type
SELECT * FROM DATA_ATTRIBUTES;
DATA_TYPE
----------
NAME
MOBILE
ETHINICITY
CC_INFO
BANK_INFO
ADDRESS
Bank_info, CC_info classified as Risk1,
Mobile, Ethinicity classified as Risk2,
Name, Address classified as Risk3
I should get the Risk classification as output,
For eg: If any of the row contains Risk1 type then output should be Risk1,
else if any of the row contains Risk2 type then output should be Risk2,
else if any of the row contains Risk3 type then output should be Risk3
I wrote below query for this
SELECT COALESCE(COL1,COL2,COL3) FROM
(SELECT
CASE WHEN DATATYPE IN ('BANK_INFO','CC_INFO') THEN 'RISK1' ELSE NULL END AS COL1,
CASE WHEN DATATYPE IN ('MOBILE','ETHINICITY') THEN 'RISK2' ELSE NULL END AS COL2,
CASE WHEN DATATYPE IN ('NAME','ADDRESS') THEN 'RISK3' ELSE NULL END AS COL3
FROM DEMO.TPA_CLASS1) A;
The required output is: Risk1 ( Only 1 value )
Please give some idea to achieve this.
You can use conditional aggregation:
SELECT
CASE
WHEN MAX(DATATYPE IN ('BANK_INFO','CC_INFO')) = 1 THEN 'RISK1'
WHEN MAX(DATATYPE IN ('MOBILE','ETHINICITY')) = 1 THEN 'RISK2'
WHEN MAX(DATATYPE IN ('NAME','ADDRESS')) = 1 THEN 'RISK3'
END AS RISK
FROM DEMO.TPA_CLASS
I am new to mysql, here i am trying to get data from database table.
select id,txnid,amount,status from txn_details;
With above query Getting data successfully but status column getting 0 or 1 or 2, but i want 0 as failed, 1 as success and 2 as not processed.
How to change my query?
You can use a case
select id, txnid, amount,
case when status = 0 then 'failed'
when status = 1 then 'success'
else 'not processed'
end as status
from txn_details;
We can use an expression in the SELECT list. It could be a searched CASE expression e.g.
SELECT CASE t.status
WHEN 0 THEN 'failed'
WHEN 1 THEN 'success'
WHEN 2 THEN 'not processed'
ELSE 'unknown'
END AS status_name
, t.status
, t.amount
, t.txnid
FROM txn_details t
This approach is ANSI-92 standards compliant, and will work in most relational databases.
There are some other MySQL specific alternatives, such as the ELT function ...
SELECT ELT(t.status+1,'failed','success','not processed') AS status_name
, t.status
, t.amount
, t.txnid
FROM txn_details t
https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_elt
If you prefer a central point of maintenance (ie you prefer not to recode all your queries when a new status comes along) you could create a status table and either use a join or sub query to get the values, alternatively you could create a function, for example
drop table if exists txn_details,txn_status;
create table txn_details(id int, txnid int, amount int , status int);
insert into txn_details values
(1,1,10,1),(2,1,10,2),(3,1,10,4);
create table txn_status (id int, statusval varchar(20));
insert into txn_status values
(1,'success'),(2,'not processed'), (3,'failed');
drop function if exists f;
delimiter $$
create function f(instatus int)
returns varchar(20)
begin
declare rval varchar(20);
return (select
case when instatus = 1 then 'success'
when instatus = 2 then 'not processed'
when instatus = 3 then 'failed'
else 'Unknown'
end
);
select t.*,coalesce(ts.statusval,'Unknown') status
from txn_details t
left join txn_status ts on ts.id = t.status;
select t.*,coalesce((select statusval from txn_status ts where ts.id = t.status),'Unknown') status
from txn_details t;
Note the use of coalesce in case a status is not found.
Both produce this result
+------+-------+--------+--------+---------------+
| id | txnid | amount | status | status |
+------+-------+--------+--------+---------------+
| 1 | 1 | 10 | 1 | success |
| 2 | 1 | 10 | 2 | not processed |
| 3 | 1 | 10 | 4 | Unknown |
+------+-------+--------+--------+---------------+
3 rows in set (0.00 sec)
Using the function like this
select t.*, f(status) as status
from txn_details t;
also produces the same result.
Of course using a status table or a function means you have to communicate their availability and enforce their use.
I would also consider the using a foreign key constraint in txn_details to cut down on the number of unknown values and put procedures in place to stop people adding new status codes at will without going through change control
The following query would work. It uses CASE ... END to determine and return values for the virtual column status.
SELECT id,txnid,amount,
CASE
WHEN status = 0 THEN 'failed'
WHEN status = 1 THEN 'success'
WHEN status= 2 THEN 'not processed'
END AS status
FROM txn_details;
I have a MySQL database with a table named generations the structure of the table is as follows
I want to get value 10 as output when ten_generation have value 1 otherwise it will not return any value, 20 as output if twenty_generation have value 1 otherwise it will not return any value, 30 as output if thirty_generation have value 1 otherwise it will not return any value. If all the three fields has a value 1 output will be 10,20,30 also the task_id will provided as the input.
Its unclear what you intend the output to be when multiple generation columns are 1 but one solution is to use a CASE statement:
SELECT CASE
WHEN ten_generation = 1 THEN 10
WHEN twenty_generation = 1 THEN 20
WHEN thirty_generation = 1 THEN 30
ELSE NULL
END AS value
FROM generations
WHERE id = :your_id
If you want it as multiple columns then:
SELECT CASE
WHEN ten_generation = 1
THEN 10
ELSE NULL
END AS ten_value,
CASE
WHEN twenty_generation = 1
THEN 20
ELSE NULL
END AS twenty_value,
CASE
WHEN thirty_generation = 1
THEN 30
ELSE NULL
END AS thirty_value
FROM generations
WHERE id = :your_id
if only twenty_generation contain value 1 the output is 20 and if twenty_generation and ten_generation contain value 1 output is 10,20
Oracle Query:
SELECT TRIM(
LEADING ',' FROM
CASE WHEN ten_generation = 1 THEN '10' END
|| CASE WHEN twenty_generation = 1 THEN ',20' END
|| CASE WHEN thirty_generation = 1 THEN ',30' END
) AS value
FROM generations
WHERE id = :your_id
For MySQL you'd use CONCAT_WS:
select
concat_ws(',',
case when ten_generation = 1 then '10' end,
case when twenty_generation = 1 then '20' end,
case when thirty_generation = 1 then '30' end
) as result
from mytable
where task_id = 2;
I want to know which condition from where clause of SQL query fails.
For example I have below statement
SELECT * from Users where status != 'inactive'
AND ptype != 'test' AND ptype != 'test1'
AND (p_name NOT IN ('ptest', 'ptest0', 'ptest1', 'ptest2') OR p_name IS NULL)
AND (p_m_c NOT LIKE '%pmcestt%'
OR (ptype LIKE 'SomeOthertest%' AND p_m_c IS NULL)
OR (TType = 'Broad' AND p_m_c IS NULL)
OR p_m_c IN ('pmctest', 'pmctest0', 'pmctest1', 'pmctest2', 'pmctest3',
'pmctest4', 'pmctest5', 'pmctest6', 'pmctest7', 'pmctest8'))
How can I know which condition failed, and get that condition?
If you want to check conditions you will have to move condition statement in WHERE clause to CASE statement for each condition in SELECT list apart from columns of table Users.
SELECT *,
CASE WHEN status !='inactive' THEN 1 else 0 end as statusTag,
CASE WHEN ptype !='test' THEN 1 ELSE 0 end as ptypeTag,
.
.
CASE WHEN p_m_c IN ('pmctest', 'pmctest0', 'pmctest1', 'pmctest2', 'pmctest3',
'pmctest4', 'pmctest5', 'pmctest6', 'pmctest7', 'pmctest8') THEN 1 else 0 end as p_m_cTag
FROM Users
This will generate list of columns for each table row indicating value 1 if condition is satisfied or 0 if condition is false for that particular row.
I have a table that, due to the third party system we are using, sometimes has duplicate data. Since the model uses an EAV method there's no way to filter this the "right" way, so I am aggregating the data into a View - I know this is a data collection problem but it's easier for me to fix it on the display end than go through this system and potentially break existing data and forms. I need to check one of two fields to see if one or both are entered, but only pick one (otherwise the name displays twice like this: "John,John" instead of just "John"). Here's my code for the relevant part:
group_concat(
(
case when (`s`.`fieldid` = 2) then `s`.`data`
else
case when (`s`.`fieldid` = 35) then `s`.`data`
else NULL end
end
) separator ','),_utf8'') as first_name
If both fieldid 2 and fieldid 35 are entered, I would expect this to just return the value from fieldid = 2 and not the value from fieldid = 35, since the Else clause shouldn't execute when the original case when is true. However it's grabbing that, and then still executing the case when inside of the else clause?
How can I fix this code to give me either fieldid = 2 OR fieldid = 35, but avoid globbing them both together which results in the name being duplicated?
EDIT
Here is the table structure:
table: subscribers_data
subscriberid (int) fieldid (int) data (text)
It uses an E-A-V structure so a sample record might be:
subscriberid fieldid data
1 2 John
1 3 Smith
1 35 John
1 36 Smith
with fieldid 2 and 35 being the custom field "First Name" (defined in a separate table) and fieldid 3 and 36 being "Last Name".
Here is the full view that I'm using:
select `ls`.`subscriberid` AS `id`,
left(`l`.`name`,(locate(_utf8'_',`l`.`name`) - 1)) AS `user_id`,
ifnull(group_concat((
case when (`s`.`fieldid` = 2) then `s`.`data`
when (`s`.`fieldid` = 35) then `s`.`data`
else NULL end) separator ','),_utf8'') AS `first_name`,
ifnull(group_concat((
case when (`s`.`fieldid` = 3) then `s`.`data`
when (`s`.`fieldid` = 36) then `s`.`data`
else NULL end) separator ','),_utf8'') AS `last_name`,
ifnull(`ls`.`emailaddress`,_utf8'') AS `email_address`,
ifnull(group_concat((
case when (`s`.`fieldid` = 81) then `s`.`data`
else NULL end) separator ','),_utf8'') AS `mobile_phone`,
ifnull(group_concat((
case when (`s`.`fieldid` = 100) then `s`.`data`
else NULL end) separator ','),_utf8'') AS `sms_only`
from ((`list_subscribers` `ls`
join `lists` `l` on((`ls`.`listid` = `l`.`listid`)))
left join `subscribers_data` `s` on((`ls`.`subscriberid` = `s`.`subscriberid`)))
where (left(`l`.`name`,(locate(_utf8'_',`l`.`name`) - 1)) regexp _utf8'[[:digit:]]+')
group by `ls`.`subscriberid`,`l`.`name`,`ls`.`emailaddress`
The view is being used as the Model for a Ruby on Rails application, so I'm using some creative hacking to fake out a "user_id" that Rails expects (we name the field list.name in the Lists table using a numeric ID that our front-end Rails app generates when we add a new user, so I'm extracting just this number to make the view look like a Rails-convention database table)
I am not a mysql guy, but in a sql server case statement, you could do it without the first 'else'
case
when fieldid = 2 then data
when fieldid = 35 then data
else null
end
Also, you seem to be returning the same 'data' field in both cases
Anything inside group_concat() doesn't have a way to see the context in which it's running. So, you have have two rows in a single group, one with fieldid=2 and second with fieldid=35, it will do the following:
processing row with fieldid=2...
s.fieldid = 2 is true, return s.data
processing row with fieldid=35...
s.fieldid = 2 is false, try the else part
s.fieldid = 35 is true, return s.data
This explains why is "John" returned multiple times. The only way to fix it is to run a different query outside of group_concat().
EDIT:
Ih you really have to do it this way, use something like this instead:
SELECT ...
min(CASE WHEN s.fieldid IN (2,35) THEN s.data ELSE NULL END) AS first_name
...
Alternatively you can do group_concat(DISTINCT ...) if the two values can't be different (otherwise you would get e.g. "John,Johny"). Why do you have two values for first_name/last_name though?