SQL Convert a char to boolean - mysql

I have in my table one row with a char value. When the value is NULL then a false should be outputted. If the value is not NULL then a true should be outputted.
So when I try to set user_group.tUser to 0 or 1 then I'm getting this error:
Invalid column name 'false'.
Invalid column name 'true'.
SELECT COALESCE((SELECT name
FROM v_company
WHERE companyId = userView.companyId), ' ') AS company,
userView.value AS companyUser,
userView.display AS displayedUser,
CASE
WHEN user_group.tUser IS NULL THEN 0
ELSE 1
END AS userIsMemberOfGroup
FROM v_user userView
LEFT OUTER JOIN cr_user_group user_group
ON ( user_group.group = 'Administrators'
AND user_group.tUser = userView.value )
ORDER BY company ASC,
displayedUser ASC

I think this is the logic you want:
SELECT COALESCE(v.name, ' ') as company,
u.value as companyUser, u.display as displayedUser,
(EXISTS (SELECT 1
FROM cr_user_group ug
WHERE ug.group = 'Administrators' AND
ug.tUser = uv.value
)
) as userIsMemberOfGroup
FROM v_user u LEFT JOIN
v_company c
ON c.companyId = v.companyId
ORDER BY company ASC, displayedUser ASC ;
In general, MySQL is very flexible about going between booleans and numbers, with 0 for false and 1 for true.

You can use MySQL IF function to return 'false' when name IS NULL, else 'true':
SELECT IF(name IS NULL, 'false', 'true')
FROM table;

A simple CASE expression would work here:
SELECT
name,
CASE WHEN name IS NOT NULL THEN true ELSE false END AS name_out
FROM yourTable;
We could also shorten the above a bit using IF:
IF(name IS NOT NULL, true, false)

SELECT
CASE
WHEN name IS NULL THEN 'false'
ELSE 'true'
END
FROM
table1;

Related

Sql add condition IF

I have sql like :
SELECT * FROM leads_notes WHERE content <> '' AND lead_id <> ''
I need add rule if type <> close_task then write user_change_task_status IS NULL
My result sql is:
SELECT * FROM leads_notes WHERE content <> '' AND lead_id <> '' IF(task_type <> 'close_task', 'AND user_change_task_status IS NULL',)
But i get many errors.
Cant understand how can i solve this. Please help, thanks!
Don't use if. Boolean logic is sufficient:
WHERE content <> '' AND
lead_id <> '' AND
( type = 'close_task' or user_change_task is null)
Or:
WHERE content <> '' AND
lead_id <> '' AND
NOT ( type = 'close_task' and user_change_task is not null )

Stored Procedure returns Empty result set on Optional paramaters

When I pass all the values required in query in return correct results. But when I only pass the ID, I get an empty result set. Shouldn't it be ignore the type in that case and still return the correct values?
Can you help me out with this and point out the issues in the query.
SELECT 'elementary_school' AS type, elementary_school AS obj, COUNT(*) AS count
FROM data
WHERE data.report_id = ReportId
AND (data.book_section = type
OR data.book_section IS NULL
OR data.book_section = ''
)
GROUP BY elementary_school
UNION
SELECT 'middle_school' AS type, middle_school AS obj, COUNT(*) AS count
FROM data
WHERE data.report_id = ReportId
AND (data.book_section = type
OR data.book_section IS NULL
OR data.book_section = ''
)
GROUP BY middle_school
UNION
SELECT 'high_school' AS type, high_school AS obj, COUNT(*) AS count
FROM data
WHERE data.report_id = ReportId
AND (data.book_section = type
OR data.book_section IS NULL
OR data.book_section = ''
)
GROUP BY high_school
UNION
SELECT 'lot_sqft' AS type, lot_sqft AS obj, COUNT(*) AS count
FROM data
WHERE data.report_id = ReportId
AND (data.book_section = type
OR data.book_section IS NULL
OR data.book_section = ''
)
GROUP BY lot_sqft
ORDER BY count, type
You can simplify the query:
SELECT t.type,
(CASE WHEN t.type = 'elementary_school' THEN elementary_school
WHEN t.type = 'middle_school' THEN middle_school
WHEN t.type = 'high_school' THEN high_school
WHEN t.type = 'lot_sqft' THEN lot_sqft
END) AS obj, COUNT(*) AS count
FROM data d CROSS JOIN
(SELECT 'elementary_school' AS type UNION ALL
SELECT 'middle_school' AS type UNION ALL
SELECT 'high_school' AS type UNION ALL
SELECT 'lot_sqft' AS type
) t
WHERE d.report_id = #ReportId AND
(d.book_section = #type OR
d.book_section IS NULL OR
d.book_section = ''
)
GROUP BY t.type. obj;
I have highlighted what seem to be "parameters" using # to clarify that they are parameters and not columns in tables.
If you want to check for a NULL value, then change the logic to:
WHERE (d.report_id = #ReportId OR #ReportId IS NULL) AND
(d.book_section = #type OR
d.book_section IS NULL OR
d.book_section = ''
)
Well, It was a silly but honest mistake. I was able to figure it out myself. The problem was I was checking if the column was null or empty but not checking on the value I passed. So it would be something like as follows:
AND (data.book_section = type
OR data.book_section IS NULL
OR data.book_section = ''
)
Converted To:
AND (data.book_section = type
OR type IS NULL
OR type = ''
)
As I only want to check if it was the 'type' which I'm passing a param is empty or null. Anyways way thanks for everyone who tried to help. Cheers.

Passing parameter to a table-valued function

I am trying to pass a parameter value to a table-valued function which has four parameters and "returns table". However, I receive following error when I pass a parameter value to one of its varchar parameter:
Msg 8114, Level 16, State 5, Line 6 Error converting data type varchar
to bigint.
declare #Scenario1 as varchar(30)
set #Scenario1 = '2017_B01'
select *
From [dbo].[fn_GetAEAssumptionFacts](#Scenario1,null,null,null) fng
Glimpse at function:
CREATE FUNCTION [dbo].[fn_GetAEAssumptionFacts]
(
#pScenarioName varchar(500) = NULL
,#pBuildingID varchar(500) = NULL
,#pLeaseID varchar(500) = NULL
,#pTenantName varchar(500) = NULL
)
RETURNS TABLE
AS
RETURN
select
.....
from ae11.dbo.rvw_FinancialLineItems fli
....
INNER JOIN ae11.dbo.rvw_Scenarios s on s.Id = pas.ScenarioId
left join
(select
externalID,
PropertyAssetId,
LeaseID,
BeginDate
from ae11.dbo.ivw_Leases
WHERE PropertyAssetID IN
(select ID from AE11.dbo.PropertyAssets where scenarioID =
(CASE WHEN isnull(#pScenarioName, '') = ''
THEN (select ID from AEX.[dbo].[ConfigurationFieldTable]
where [Type] = 'Lease Connect Current Scenario' )
ELSE #pScenarioName
END)
)
) lea
ON lea.LeaseID = uni.ExternalID
AND lea.PropertyAssetID = uni.PropertyAssetId
where 1=1
......
AND s.id = (CASE WHEN isnull(#pScenarioName, '') = ''
THEN (select ID from AEX.[dbo].[ConfigurationFieldTable]
where [Type] = 'Lease Connect Current Scenario' )
ELSE #pScenarioName
END)
Here
(CASE WHEN isnull(#pScenarioName, '') = ''
THEN (select ID from AEX.[dbo].[ConfigurationFieldTable]
where [Type] = 'Lease Connect Current Scenario' )
ELSE #pScenarioName
END)
You are taking a value depending on #ScenarioName. This will either be the result of select ID from AEX.[dbo].[ConfigurationFieldTable] WHERE... or the content of #ScenarioName.
I assume, that this ID is a bigint, while your #SenarioName is a string. And the s.ID you want to compare it against - I don't know...
But - to be honest - my magic crystall ball is out for cleaning and the information you provide is not enough.

SQL Server Row totals in pivot query

I am trying to make a row in the end of the result set that shows the totals.
My query is this:
SELECT
[ ] = ISNULL(CAST(GEN_idPaciente AS VARCHAR)+'-'+nombrePaciente, 'TOTAL'),
[2016-11-01] = MAX([2016-11-01]),
[2016-11-02] = MAX([2016-11-02]),
[2016-11-03] = MAX([2016-11-03]),
[2016-11-04] = MAX([2016-11-04]),
TOTAL = COUNT([2016-11-01]) + COUNT([2016-11-02]) + COUNT([2016-11-03]) + COUNT([2016-11-04])
FROM
(
SELECT GEN_Paciente.GEN_idPaciente,COALESCE(GEN_ape_paternoPaciente, '')+' '+COALESCE(GEN_ape_maternoPaciente, '')+' '+COALESCE(GEN_nombrePaciente, '') AS nombrePaciente,HOS_fechaCategorizacion,HOS_nivel_riesgoCategorizacion+CAST(HOS_nivel_dependenciaCategorizacion AS VARCHAR) as riesgoDependencia
FROM HOS_Categorizacion
INNER JOIN HOS_Hospitalizacion
ON HOS_Hospitalizacion.HOS_idHospitalizacion = HOS_Categorizacion.HOS_idHospitalizacion
INNER JOIN GEN_Paciente
ON GEN_Paciente.GEN_idPaciente = HOS_Hospitalizacion.GEN_idPaciente
WHERE HOS_nivel_riesgoCategorizacion IS NOT NULL
) src
PIVOT
(
MAX(riesgoDependencia)
for HOS_fechaCategorizacion in ([2016-11-01],[2016-11-02],[2016-11-03],[2016-11-04])
) p
GROUP BY
ROLLUP(CAST(GEN_idPaciente AS VARCHAR)+'-'+nombrePaciente)
This gives me this result:
But as you can see the totals for the rows are right but the totals for the columns are wrong because I am using MAX instead of COUNT, but I only need COUNT in the TOTAL row, the others have to be MAX, so I wrote this query:
SELECT
[ ] = ISNULL(CAST(GEN_idPaciente AS VARCHAR)+'-'+nombrePaciente, 'TOTAL'),
[2016-11-01] = CASE WHEN CAST(GEN_idPaciente AS VARCHAR)+'-'+nombrePaciente IS NOT NULL THEN MAX([2016-11-01]) ELSE COUNT([2016-11-01]) END,
[2016-11-02] = CASE WHEN CAST(GEN_idPaciente AS VARCHAR)+'-'+nombrePaciente IS NOT NULL THEN MAX([2016-11-02]) ELSE COUNT([2016-11-02]) END,
[2016-11-03] = CASE WHEN CAST(GEN_idPaciente AS VARCHAR)+'-'+nombrePaciente IS NOT NULL THEN MAX([2016-11-03]) ELSE COUNT([2016-11-03]) END,
[2016-11-04] = CASE WHEN CAST(GEN_idPaciente AS VARCHAR)+'-'+nombrePaciente IS NOT NULL THEN MAX([2016-11-04]) ELSE COUNT([2016-11-04]) END,
TOTAL = COUNT([2016-11-01]) + COUNT([2016-11-02]) + COUNT([2016-11-03]) + COUNT([2016-11-04])
FROM
(
SELECT GEN_Paciente.GEN_idPaciente,COALESCE(GEN_ape_paternoPaciente, '')+' '+COALESCE(GEN_ape_maternoPaciente, '')+' '+COALESCE(GEN_nombrePaciente, '') AS nombrePaciente,HOS_fechaCategorizacion,HOS_nivel_riesgoCategorizacion+CAST(HOS_nivel_dependenciaCategorizacion AS VARCHAR) as riesgoDependencia
FROM HOS_Categorizacion
INNER JOIN HOS_Hospitalizacion
ON HOS_Hospitalizacion.HOS_idHospitalizacion = HOS_Categorizacion.HOS_idHospitalizacion
INNER JOIN GEN_Paciente
ON GEN_Paciente.GEN_idPaciente = HOS_Hospitalizacion.GEN_idPaciente
WHERE HOS_nivel_riesgoCategorizacion IS NOT NULL
) src
PIVOT
(
MAX(riesgoDependencia)
for HOS_fechaCategorizacion in ([2016-11-01],[2016-11-02],[2016-11-03],[2016-11-04])
) p
GROUP BY
ROLLUP(CAST(GEN_idPaciente AS VARCHAR)+'-'+nombrePaciente)
But that is not working
Thanks for your help!!
If I understand this correctly you want to count all columns which are not null. In this case you should just look at the condition IS NULL and not at the actual value at all. Try this:
DECLARE #tbl TABLE(ID INT IDENTITY, val1 VARCHAR(100),val2 VARCHAR(100),val3 VARCHAR(100));
INSERT INTO #tbl VALUES
('row1_val1','row1_val2',NULL)
,('row2_val1','row2_val2','row2_val3')
,(NULL,'row2_val2',NULL)
,(NULL,NULL,'row2_val3')
,(NULL,NULL,NULL);
SELECT *
,CASE WHEN val1 IS NULL THEN 0 ELSE 1 END
+CASE WHEN val2 IS NULL THEN 0 ELSE 1 END
+CASE WHEN val3 IS NULL THEN 0 ELSE 1 END AS CountOfValNotNull
FROM #tbl
UPDATE: Add a final Totals Row
You'd need ugly fiddling with a CTE, an additional sort column, UNION ALL to add another row and a sub_select.
Use the outer-most ORDER BY to get the artificial Totals-Row to the end
hint: Use the #tbl variable from above!
WITH SortedRows AS
(
SELECT ROW_NUMBER() OVER(ORDER BY ID) AS SortColumn
,*
,CASE WHEN val1 IS NULL THEN 0 ELSE 1 END
+CASE WHEN val2 IS NULL THEN 0 ELSE 1 END
+CASE WHEN val3 IS NULL THEN 0 ELSE 1 END AS CountOfValNotNull
FROM #tbl
)
SELECT tbl1.*
FROM
(
SELECT * FROM SortedRows
UNION ALL
SELECT 999999,0,'','','',(SELECT SUM(CountOfValNotNull) FROM SortedRows)
) AS tbl1
ORDER BY tbl1.SortColumn

Need to write MySQL case statement

I need to write a MySQL statement, but not sure how to write it using case statements.
I would like to write something like this:
SELECT
*
FROM
table
WHERE:
IF sign_off_1 IS NOT NULL AND sign_off_1 IS NOT EQUAL TO 'Director'
sign_off_1_status MUST BE EQUAL TO Complete
IF sign_off_2 IS NOT NULL AND sign_off_2 IS NOT EQUAL TO 'Director'
sign_off_2_status MUST BE EQUAL TO Complete
IF sign_off_3 is IS NOT NULL AND sign_off_3 IS NOT EQUAL TO
'Director' sign_off_3_status MUST BE EQUAL TO Complete
Does anyone know the correct syntax to write this query?
It's not clear what you want to achieve. Does a row need to satisfy all three conditions, or just one of them? Either result can be achieved without using CASE expressions.
If the requirement is to use CASE expressions, and you need all three conditions to be true, you could do something like this:
SELECT t.id
FROM mytable t
WHERE CASE
WHEN t.sign_off_1 <> 'Director' AND t.sign_off_1_status = 'Complete'
THEN 1
ELSE 0
END
+ CASE
WHEN t.sign_off_2 <> 'Director' AND t.sign_off_2_status = 'Complete'
THEN 1
ELSE 0
END
+ CASE
WHEN t.sign_off_3 <> 'Director' AND t.sign_off_3_status = 'Complete'
THEN 1
ELSE 0
END
= 3
If you only need one of the conditions to be true, you could replace = 3 with > 0.
Note that an inequality comparison to a literal is sufficient to guarantee the column is not null. (If the column is NULL, the inequality comparison will return NULL, rather than TRUE.)
Again, the same result could be achieved without using CASE expressions.
You need to use OR and AND operator to simulate if condition in where clause. Try this.
SELECT *
FROM table
WHERE ( sign_off_1 <> 'Director'
AND sign_off_1_status = 'Complete' )
OR ( sign_off_2 <> 'Director'
AND sign_off_2_status = 'Complete' )
OR ( sign_off_3 <> 'Director'
AND sign_off_3_status = 'Complete' )
OR ( sign_off <> 'Director'
AND status <> 'Complete')
Update: am not completely sure about your comment. But this is what i understood.
WHERE (( sign_off_1 <> 'Director'
AND sign_off_1_status = 'Complete' )
OR ( sign_off_2 <> 'Director'
AND sign_off_2_status = 'Complete' )
OR ( sign_off_3 <> 'Director'
AND sign_off_3_status = 'Complete' ))
AND ( sign_off <> 'Director'
AND status <> 'Complete')