ERROR: division by zero + PostgreSQL + Rails - sql

I'm getting the following error when I run this database view in psql (ERROR: division by zero). Even I can't access my table in rails console If anyone has any solution for this error so please comment on it will be very helpful thanks in advance.
select
(exam_id || '00' || quarter)::bigint as id,
account_id,
exam_id,
quarter,
quarter_label,
count(id) as assessments,
max(banding_percentage) as top_assessment_percentage,
min(banding_percentage) as bottom_assessment_percentage,
round(avg(banding_percentage),2) as avg_assessment_percentage
from report_assessments
group by account_id, exam_id, quarter, quarter_label;

To avoid running into division by zero exceptions you should use nullif, so that you can catch this 0 and replace it by null, e.g.
WITH j (v1,v2) AS (
VALUES (1.0,0.0),(10.0,3.0)
)
SELECT v1/nullif(v2,0) AS div FROM j;
div
--------------------
3.3333333333333333
(2 Zeilen)

You Need to do something like this.
It works in my case:
Negotiation.find(
:all,
conditions: conditions_hash('negotiation'),
select:
'CASE
sum(banding_percentage)
WHEN
0
THEN
NULL
ELSE
sum(total_percentage) / sum(banding_percentage)
END as error_check'
).first

Related

teradata - invalid select expression list

Trying to make a select query on teradata, but i get this message error:
syntax error: invalid select expression list
I can't fix it. How can I formulate the query appropriately?
SELECT BILS01_GRADO, BILS01_CODICE_COM, BILS01_PROT, BILS01_PROG_OGG_IMP,BILS01_PROG_REC,
CASE WHEN BILS01_DATA_PRES_ISTSOSP<TO_DATE('9999-12-31','YYYY-MM-DD') AND BILS01_CTR_IST_SOSP=0 THEN BILS01_DATA_PRES_ISTSOSP
WHEN BILS01_DATA_PRES_ISTSOSP=TO_DATE('9999-12-31','YYYY-MM-DD') AND BILS01_CTR_IST_SOSP>0 THEN DATA_CONTROVERSIA2
WHEN BILS01_DATA_PRES_ISTSOSP=TO_DATE('9999-12-31','YYYY-MM-DD') AND BILS01_CTR_IST_SOSP=0 THEN TO_DATE('9999-12-31','YYYY-MM-DD')
WHEN BILS01_DATA_PRES_ISTSOSP<
(
CASE WHEN
(
CASE WHEN BILS01_DATA_SPED<to_date('9999-12-31','YYYY-MM-DD') THEN BILS01_DATA_SPED
WHEN BILS01_DATA_SPED=to_date('9999-12-31','YYYY-MM-DD') OR BILS01_DATA_RIC<to_date('9999-12-31','YYYY-MM-DD')THEN BILS01_DATA_RIC
WHEN BILS01_DATA_ACQ<to_date('9999-12-31','YYYY-MM-DD') THEN BILS01_DATA_ACQ ELSE BILS01_DATA_PROT END AS DATA_CONTROVERSIA
)
<TO_DATE('1972-01-01','YYYY-MM-DD') THEN TO_DATE('1972-01-01','YYYY-MM-DD') ELSE DATA_CONTROVERSIA END AS DATA_CONTROVERSIA2
)
THEN BILS01_DATA_PRES_ISTSOSP ELSE DATA_CONTROVERSIA2 END AS A) AS OUT_DATA_RICH_SOSP
FROM zucow.BILS01
--GROUP BY BILS01_GRADO, BILS01_CODICE_COM, BILS01_PROT, BILS01_PROG_OGG_IMP,
-- BILS01_PROG_REC, OUT_DATA_RICH_SOSP

GETTING ERROR-- ORA-00936:MISSING EXPRESSION for below query please help on this

SELECT CASE (SELECT Count(1)
FROM wf_item_activity_statuses_v t
WHERE t.activity_label IN ('WAITING_DISB_REQ',
'LOG_DDE',
'LOG_SENDBACK_DDE')
AND t.item_key IN(
SELECT r.i_item_key
FROM wf_t_item_xref r
WHERE r.sz_appl_uniqueid = '20400000988')
)
WHEN 0 THEN
(
delete
from t_col_val_document_uploaded p
WHERE p.sz_application_no = '20400000988'
AND p.sz_collateral_id = 'PROP000000000PRO1701'
AND p.i_item_key = '648197'
AND p.i_document_srno = '27' )
WHEN 1 THEN
(
DELETE
FROM t_col_val_document_uploaded p
WHERE p.sz_application_no = '20400000988'
AND p.sz_collateral_id = 'PROP000000000PRO1701'
AND p.i_document_srno = '28' )
ELSE NULL
END
FROM dual;
You need to recreate your query and make sure to follow the flow of the clauses properly, please check the next two links to get a better understanding :
[ORA-00936: missing expression tips]
How do I address this ORA-00936 error?
Answer: The Oracle oerr utility notes this about the ORA-00936 error:
ORA-00936 missing expression
Cause: A required part of a clause or expression has been omitted. For example, a SELECT statement may have been entered without a list of columns or expressions or with an incomplete expression. This message is also issued in cases where a reserved word is misused, as in SELECT TABLE.
Action: Check the statement syntax and specify the missing component.
The ORA-00936 happens most frequently:
1 - When you forget list of the column names in your SELECT statement.
2. When you omit the FROM clause of the SQL statement.
ora-00936-missing-expression
I hope this can help you.
You cannot use a simple select query like this. You have to use a PL/SQL block like below -
DECLARE NUM_CNT NUMBER := 0;
BEGIN
SELECT Count(1)
INTO NUM_CNT
FROM wf_item_activity_statuses_v t
WHERE t.activity_label IN ('WAITING_DISB_REQ',
'LOG_DDE',
'LOG_SENDBACK_DDE')
AND t.item_key IN(SELECT r.i_item_key
FROM wf_t_item_xref r
WHERE r.sz_appl_uniqueid = '20400000988');
IF NUM_CNT = 0 THEN
delete
from t_col_val_document_uploaded p
WHERE p.sz_application_no = '20400000988'
AND p.sz_collateral_id = 'PROP000000000PRO1701'
AND p.i_item_key = '648197'
AND p.i_document_srno = '27';
ELSIF NUM_CNT = 1 THEN
DELETE
FROM t_col_val_document_uploaded p
WHERE p.sz_application_no = '20400000988'
AND p.sz_collateral_id = 'PROP000000000PRO1701'
AND p.i_document_srno = '28' )
END IF;
END;

IF-ELSE SQL Statement

I'm having a problem executing this SQL statement. I am new to TSQL and I have no idea how to fix this. Everytime I execute this, I get the error:
An expression of non-boolean type specified in a context where a
condition is expected, near ')'.
Incorrect syntax near the keyword 'else'.
if
SELECT Num from users where SUBSTRING(CAST(Num AS VARCHAR(6)),1,2) = 14
print 'Batch 2014';
else
print 'Batch 2013';
What I'm trying to do here is to search in my table all users with '13' as the first 2 numbers in the column 'Num', and then print 'Batch 2014' else 'Batch 2013' Please help :) thank you
It's best to avoid using if-else with exists. Why?
You need to make sure at least one record exists in your table
The other benefit of EXISTS is that once it finds a single record that matches it stops processing. This doesn't have a huge impact if you're checking on a primary key. It does have a big impact if you're checking for existence based on another field
if exists (SELECT Num from users where SUBSTRING(CAST(Num AS VARCHAR(6)), 1, 2) = 14)
print 'Batch 2014';
else
print 'Batch 2013';`
Your if condition returns non-boolean value (other that 0 or 1),that's the reason for getting the error.
If you are using if .. exists it will print if any of the num in your table satisfies the condition SUBSTRING(CAST(Num AS VARCHAR(6)),1,2) = 14.
If you wanted to see the users with batch information ,use CASE statement.
SELECT userid,Name -- mention the columns you wanted to select
,CASE WHEN SUBSTRING(CAST(Num AS VARCHAR(6)),1,2) =14 THEN 'Batch 2014'
ELSE 'Batch 2013' END Batch
FROM users
What the type of Num?
syntax of IF-ELSE:
-- Syntax for SQL Server, Azure SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse
IF Boolean_expression
{ sql_statement | statement_block }
[ ELSE
{ sql_statement | statement_block } ]
So, "SELECT Num from users where SUBSTRING(CAST(Num AS VARCHAR(6)),1,2) = 14" should return a Boolean, True or False.
IF EXISTS (SELECT Num from users where SUBSTRING(CAST(Num AS VARCHAR(6)),1,2) = 14)
IF EXISTS ( SELECT Num
FROM users
WHERE SUBSTRING(CAST(Num AS VARCHAR(6)), 1, 2) = 14 )
PRINT 'Batch 2014' ;
ELSE
PRINT 'Batch 2013' ;

SQL Server : query if table exist

I have the following query:
SELECT
COUNT(*) over () as countNum,
[F1] AS STANDARDandOBJ,
[F2] AS CLUSTER,
[F3] AS OBJECTIVE,
[F4] AS EXTRA0
IF COL_LENGTH([tmpExcelDB].[dbo].['Blahsing$'], [F5]) IS NOT NULL
BEGIN
print 'exists'
END
ELSE
BEGIN
print 'Nope'
END,
CONCAT([F1], [F2]) AS combined
FROM
[tmpExcelDB].[dbo].['Blahsing$']
WHERE
LOWER(F3) NOT LIKE 'course tools-%'
But it seems that I have an error of:
Incorrect syntax near ','.
Which is pointing to row:
,CONCAT([F1], [F2]) AS combined
How does this need to be formatted in order to work?
You can't use IF inside a SELECT, you need a CASE expression. Also, it doesn't make sense to use PRINT inside a column:
SELECT
COUNT(*) over () as countNum
,[F1] AS STANDARDandOBJ
,[F2] AS CLUSTER
,[F3] AS OBJECTIVE
,[F4] AS EXTRA0
,CASE
WHEN COL_LENGTH('[tmpExcelDB].[dbo].[''Blahsing$'']', '[F5]') IS NOT NULL
THEN 'exists'
ELSE 'Nope'
END
,CONCAT([F1], [F2]) AS combined
FROM [tmpExcelDB].[dbo].['Blahsing$']
WHERE
LOWER(F3) NOT LIKE 'course tools-%';
SELECT
COUNT(*) over () as countNum
,[F1] AS STANDARDandOBJ
,[F2] AS CLUSTER
,[F3] AS OBJECTIVE
,[F4] AS EXTRA0 ,
( CASE When COL_LENGTH([tmpExcelDB].[dbo].['Blahsing$'], [F5]) IS NOT NULL
THEN
'exists'
ELSE
'Nope'
END),
CONCAT([F1], [F2]) AS combined
FROM [tmpExcelDB].[dbo].['0812 Orientation to Nursing$']
WHERE LOWER(F3)NOT LIKE 'course tools-%'
Couple things:
IF...ELSE is not supported in a select list, use CASE instead
PRINT is not supported in a select list, just the literal string value is needed
See the CASE Documentation for a relevant example.

SQL Server : getting an error "Msg147, level15" Why do I get this error and how to fix it

I have the following code
IF EXISTS(SELECT #FunderID
FROM dbo.FunderCharityTbl
WHERE #ContributionAmount > ( ( sum(TotalContributions) / 100 ) *10 ))
BEGIN
RAISERROR ('Sorry contribution is refused limit is breached', 16,1)
RETRUN 99
END
And I am getting the following error
Msg 147, Level 15, State 1, Procedure InsertContribution, Line 33
An aggregate may not appear in the WHERE clause unless it is in a
subquery contained in a HAVING clause or a select list, and the column
being aggregated is an outer reference.
What I am trying to do is check if the #contributionAmount (entered amount) is greater than 10% of all the previous contributions made by the person with the entered funderID and if it is send an error message
I am relatively new to SQL and am wondering why you can't write the If Exists statement the way I did write it and what do I need to do to fix this error and have my procedure perform in the same manner as I wanted.
You can't use a Aggregate function in WHERE clause, but you can use it in HAVING clause
IF EXISTS( SELECT 1 --#FunderID
FROM dbo.FunderCharityTbl
HAVING #ContributionAmount > ((sum(TotalContributions)/100)*10)
)
You have to use GROUP BY and HAVING something like:
IF EXISTS(
SELECT #FunderID
FROM dbo.FunderCharityTbl
GROUP BY #FunderID
HAVING #ContributionAmount > ((sum(TotalContributions)/100)*10)
)
I think the message is pretty clear: You cannot use an aggregation function in a where clause. The appropriate clause is having.
The intent of your query is unclear. Why are you returning a variable value? In fact, with EXISTS, you can return anything. I prefer SELECT 1.
I would guess that you are trying to determine if #FunderID has made more than a certain level of contributions. You would do this as:
IF ( (SELECT (sum(TotalContributions)/100)*10
FROM dbo.FunderCharityTbl
WHERE FunderId = #FunderId
) > #ContributionAmount
)
BEGIN
. . .
END;
Note: I also encourage you to use BEGIN/END blocks whenever you use IF.
An alternative interpretation is that you want to determine if any funder has donated more than the specified amount:
IF (EXISTS (SELECT (sum(TotalContributions)/100)*10
FROM dbo.FunderCharityTbl
GROUP BY FunderId
HAVING sum(TotalContributions)/100)*10 > #ContributionAmount
)
)
BEGIN
. . .
END;