DB2 SQL Query Filtering rows based on multiple fields - db2

I need to write a query based on the following conditions:
Within one table, the following condition must be met:
table name: DLS_RBM_RBI
columns within the table
RBM_3_CD must be blank
If RBM_3_CD is blank, then RBM_2_CD must be 1
If RBM_3_CD is blank and RBM_2_CD is blank, then RBM_1_CD must be 1
How would these conditions be coded in a SQL statement? In an IF within a where clause or case in a select?
I tried using a where clause with these conditions.
AND (D.RBM_3_CD = '')
OR (D.RBM_3_CD = '' AND D.RBM_2_CD = '1')
OR (D.RBM_3_CD = '' AND RBM_2_CD = '' AND RBM_1_CD = '1')

The first statement
AND (D.RBM_3_CD = ' ')
negates the need for the second and third. There's no way for the first statement to false while the second or third are true.
try this instead
where D.RBM_3_CD = ' '
and ( (D.RBM_3_CD = '' AND D.RBM_2_CD = '1')
or (D.RBM_3_CD = '' AND RBM_2_CD = '' AND RBM_1_CD = '1')
)

Related

Matching records by ID and displaying non-matching columns in TSQL

In SQL Server I have two tables, Registrar Records and Teacher Records which are identical. The first part of the query matches on the student ID and shows whether or not a match was found in a dynamic column (that part I did already).
An additional dynamic column should list out all the columns that didn't match - I'm wondering if there is a way to do this without making a gigantic Case expression since that would have many possibilities, this is what I have so far:
SET ANSI_NULLS OFF
SELECT TR.*,
CASE WHEN RR.StudentID IS NULL THEN 'NO MATCH'
WHEN RR.StudentID IS NOT NULL AND RR.FirstName = TR.FirstName
AND RR.LastName = TR.LastName
AND RR.Floor = TR.Floor
AND RR.FirstQuarterGrade = TR.FirstQuarterGrade
AND RR.SecondQuarterGrade = TR.SecondQuarterGrade
AND RR.ThirdQuarterGrade = TR.ThirdQuarterGrade
AND RR.FinalGrade = TR.FinalGrade THEN 'MATCH'
ELSE 'MATCH WITH ISSUE' END AS MatchResult
--TO DO: Add a ISSUE column; lists columns with mismatch
FROM TeacherRecords TR
LEFT JOIN RegistrarRecords RR ON RR.StudentID = TR.StudentID
If a script is needed for the table here is the table:
CREATE TABLE [dbo].[RegistrarRecords](
[StudentID] [varchar](10) NOT NULL,
[FirstName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
[Floor] [int] NULL,
[Room] [varchar](10) NULL,
[FirstQuarterGrade] [int] NULL,
[SecondQuarterGrade] [int] NULL,
[ThirdQuarterGrade] [int] NULL,
[FinalGrade] [int] NULL
) ON [PRIMARY]
You could split this query into two parts
First find all the issues
Then check if there are any issues in doing the final select
Here is sample code to do so. The Issue_List field contains a comma-separated list of all the columns with issues (e.g., 'Floor, FirstQuarterGrade'). If this field is empty, then it represents that there are no issues.
WITH TR_Match_Info AS
(SELECT TR.*,
RR.StudentID AS RR_StudentID,
'' + CASE WHEN RR.FirstName = TR.FirstName THEN '' ELSE 'FirstName, ' END
+ CASE WHEN RR.LastName = TR.LastName THEN '' ELSE 'LastName, ' END
+ CASE WHEN RR.Floor = TR.Floor THEN '' ELSE 'Floor, ' END
+ CASE WHEN RR.FirstQuarterGrade = TR.FirstQuarterGrade THEN '' ELSE 'FirstQuarterGrade, ' END
+ CASE WHEN RR.SecondQuarterGrade = TR.SecondQuarterGrade THEN '' ELSE 'SecondQuarterGrade, ' END
+ CASE WHEN RR.ThirdQuarterGrade = TR.ThirdQuarterGrade THEN '' ELSE 'ThirdQuarterGrade, ' END
+ CASE WHEN RR.FinalGrade = TR.FinalGrade THEN '' ELSE 'FinalGrade, ' END
AS Issue_List
FROM TeacherRecords TR
LEFT JOIN RegistrarRecords RR ON RR.StudentID = TR.StudentID
)
SELECT [StudentID],
[FirstName],
[LastName],
[Floor],
[Room],
[FirstQuarterGrade],
[SecondQuarterGrade],
[ThirdQuarterGrade],
[FinalGrade],
CASE WHEN RR_StudentID IS NULL THEN 'NO MATCH'
WHEN Issue_List = '' THEN 'MATCH'
ELSE 'MATCH WITH ISSUE' END
AS MatchResult,
CASE WHEN RR_StudentID IS NULL THEN ''
WHEN LEN(Issue_List) > 0 THEN LEFT(Issue_List, LEN(Issue_List) - 1)
ELSE Issue_List
END AS Match_Issues
FROM TR_Match_Info;
Note that the issue checks above are based on your code. You should review how NULLs are handled - if the values are both NULL it flags it as an issue (e.g., when checking whether NULL = NULL the result is NULL so it goes to the ELSE component of these CASE expressions).

How to fix an expression of non-boolean type specified in a context where a condition is expected, near 'BEGIN'.?

Hey I have this query
IF (select kmkood from or_arved_read where kmkood = '1' or kmkood = '14' or kmkood = '15' or kmkood = '6' )
BEGIN
SET #stat_vat = 21
IF (select kmkood from or_arved_read where kmkood = '2' or kmkood = '7' )
SET #stat_vat = 12
But it returns An expression of non-boolean type specified in a context where a condition is expected, near 'BEGIN'.
how can i fix it?
Firstly, your IF doesn't have a boolean expression. The subquery returns a value (or more accurately for this scenario will return many and cause a different error) for the column kmkood, but then you don't do anything with that value. What value does that column need? The format should be something like this:
IF (SELECT SomeColumn FROM dbo.SomeTable WHERE... ) = 'SomeValue'
Also, if you have a BEGIN you need an END afterwards, which you don't have:
IF (SELECT SomeColumn FROM dbo.SomeTable WHERE... ) = 'SomeValue'
BEGIN
{Do several statements}
END
As, however, you are just doing a SET statement then you don't actually need the BEGIN and END statements.
I suspect what you are really after here, however, in an EXISTS:
IF EXISTS(SELECT 1 FROM dbo.or_arved_read WHERE kmkood IN (1,14,15,6))
SET #stat_vat = 21;
IF EXISTS(SELECT 1 FROM dbo.or_arved_read WHERE kmkood IN (2,7))
SET #stat_vat = 12;
You don't need all those ORs either, an IN works fine, and numbers shouldn't be in single quotes, so that makes things a bit shorter.

How to make a function use CASE and IFNULL in postgreSQL?

can you tell me how to use CASE and IFNULL in postgre? i'm migrating from sql to postgreSQL, and i want to make a function with this syntax :
SELECT a.furniture_id, a.furniture_brand, a.furniture_cost,
CASE
WHEN furniture_id = f_id THEN a.furniture_content
ELSE ''
END CONTENT
FROM tb_furniture a
WHERE
(IFNULL(a.sale_id,0) = IFNULL(f_id,0) OR (a.furniture_id = f_Id AND IFNULL(a.furniture_content,'') > ''))
AND a.published = 1;
thanks before(y)
This seems to be what you are after, but carefully check the WHERE conditions:
SELECT a.furniture_id, a.furniture_brand, a.furniture_cost,
CASE WHEN a.furniture_id = f_id
THEN a.furniture_content
ELSE ''
END AS content
FROM tb_furniture a
WHERE (coalesce(a.sale_id,0) = coalesce(f_id,0) OR length(content) > 0)
AND a.published = 1;

Doctrine Datetime and where condition

I am writing a Doctrine 2.3 Query and I am facing some issues:
The SQL Query which I am reflecting was:
SELECT *
FROM `entry`
WHERE `plate` LIKE '%'
AND `recognition_datetime` BETWEEN '2013-03-13 22:20:18'
AND '2013-03-13 22:20:20';
I am getting the out put with the rows selected.
Doctrine which I am trying:
Opt 1:
$qry = $this->manager()->createQueryBuilder()
->from($this->entity, 'e')
->select('e');
$qry->where('e.plate like :plate');
$qry->setParameter('plate', $plate);
$qry->add('where', "e.datetime between '2013-03-13 22:20:18' and '2013-03-13 22:20:20'");
$qry->setMaxResults( $limit );
It out puts only the first where condition:
SELECT e FROM Myproject\Domain\result e WHERE e.plate like '%'
Opt 2:
$qry = $this->manager()->createQueryBuilder()
->from($this->entity, 'e')
->select('e');
$qry->where('e.plate like :plate');
$qry->setParameter('plate', $plate);
$qry->andWhere('e.datetime BETWEEN :monday AND :sunday')
->setParameter('monday', $fromdate->format('Y-m-d H:i:s'))
->setParameter('sunday', $todate->format('Y-m-d H:i:s'));
It prints only the second where as query. Can some one help me how to write multiple where/And/or condition?
After some Research I found few thing which solved my problems:
Query Generation:
//CREATING QUERY BUILDER
$qry = $this->manager()->createQueryBuilder()
->from('YOUR_ENTITY_HERE', 'e')
->select('e');
//LIKE
$ex1 = $qry->expr()->like('e.user', "'".$user."'");
//BETWEEN
$ex2 = $qry->expr()->between('e.datetime',"'".$datetime."'","'".$dateto."'");
//IN
$ex3 = $qry->expr()->in('e.country', $country);
//ADDING ALL EXPRESSION TO ONE INBETWEEN EXPRESSION "AND" OPERATION
$Query = $qry->expr()->andX($ex1,$ex2,$ex3);
//ADDING ALL EXPRESSION TO ONE INBETWEEN EXPRESSION "OR" OPERATION
$Query = $qry->expr()->orX($ex1,$ex2,$ex3);
//ADDING TOTAL EXPRESSIONS TO WHERE
$qry->where($Query);
//GENERATE QUERY
$qry->getQuery();
//FINAL OPERATIONS
//EXECUTE
$qry->execute();
//GET ARRAY OUT PUT
$qry->getArrayResult();
//GET DB OBJECT
$qry->getResult();
Other Methods for Providing IN Operations:
OTHER WAY TO USE IN OPERATION:
$country=array('Us','UK','IND','BE');
$exp = $this->manager()->getExpressionBuilder();
$qry = $this->manager()->createQueryBuilder()
->select('e')
->from('YOUR_ENTITY_HERE', 'e')
->add('where', $exp->in('e.country', $country));

Zend: How to use 'not equal to' in WHERE clause?

I am using following zend code to select all data from a table where verified=1 and it is working for me.
$table = $this->getDbTable();
$select = $table->select();
$select->where('verified = 1');
$rows = $table->fetchAll($select);
No I want to select all data from that table where verified is not equal to '1'. I have tried the following ways but it is not fetching data.
$select->where('verified != 1');
$select->where('verified <> 1');
$select->where('verified != ?', 1);
Data structure for 'verified' column:
Field: verified
type: varchar(45)
Collation: utf8_bin
NULL: Yes
Default: NULL
Any idea that how to use 'not equal to' operator in WHERE clause in Zend? Thanks
$select->where('verified != ?', 1);
Real worls query example:
$query = $this->getDb()->select();
$query->from('title', array('title_id' => 'id', 'title', 'production_year', 'phonetic_code'))
->where('kind_id = 1')
->where('title = ?', trim($title))
->where('production_year != ?', '2009')
->limit(1)
;
Selects movies info from IMDB database. Works fine.
MySQL supports a custom operator <=> which returns true if the operands are equal or both null. It returns false if they are different, or if one operand is null.
$select->where('verified <=> 1');
This operator is non-standard. Standard SQL has syntax: IS NOT DISTINCT FROM that works just like MySQL's <=>.
Since your column is a varchar perhaps try where verified != '1' or verified is null
Can you show us the table structure for the table you are querying? Is the column verified an int or string? Also try printing the SQL statement that ZEND builds, see the echo line below.
$table = $this->getDbTable();
$select = $table->select();
$select->where('verified = 1');
echo sprintf("sql %s",$select);
$rows = $table->fetchAll($select);
Try :
$select->where('verified != ?', '1');
put quotation marks around the value. It is working for me.