Using an IF statement within a WHERE clause - if-statement

I want to show all propID live today.
I have DateLive & DateRemoved for each propID on the PC table but some have a NULL DateRemoved (as they are still live).
I need to use an IF (CASE) statement in my WHEREe to do this.
Something like...
Where it's today,
AND (IF they don't have a DateRemoved) then datelive < CalendarDate
OR IF they do have a Date Removed then CalendarDate is Between DateLive and DateRemoved)
SELECT
C.CalendarDate,
PC.propID
FROM Calendar C
CROSS join PropertyCounts PC
Where C.CalendarDate = getdate()
AND
(CASE
WHEN PC.DateRemoved <>NULL THEN C.CalendarDate BETWEEN PC.DateLive AND PC.Dateremoved
WHEN PC.DateRemoved = NULL THEN PC.DateLive < C.CalendarDate )

where C.CalendarDate = getdate()
AND ((PC.DateRemoved is not null AND C.CalendarDate between PC.DateLive AND PC.Dateremoved)
OR
(PC.DateRemoved is null AND PC.DateLive < C.CalendarDate)
)
You're already in an IF statement of sorts with the Where clause. You simply need to build the boolean logic that evaluates to TRUE when a particular record should be selected.

Try to insert this on your where clause substituting the case in parenthesis:
... and ((pc.dateremoved IS NOT NULL and c.calendarDate between pc.datelive and pc.dateremoved) or (pc.dateremoved IS NULL and pc.datelive < c.calendardate))

You don't need the complexity of a CASE expression (or an IF statement), just boolean logic with AND and OR
Where C.CalendarDate = getdate()
AND
(
(PC.DateRemoved IS NOT NULL AND
C.CalendarDate BETWEEN PC.DateLive AND PC.Dateremoved)
OR
(PC.DateRemoved IS NULL AND PC.DateLive < C.CalendarDate)
)
You might also need to do some fiddling around to remove the time component from getdate(), e.g. your first condition might need to be:
Where C.CalendarDate = CONVERT(date,getdate())
because getdate() returns a datetime with both parts populated, not just a plain date with no time component.

Related

Update columns based on condition PL/SQL setting them as NULL

I wanted to update columns based on condition: There is this table with columns A, B, C, D, E.
These columns with values are to be updated with null. I do not want to touch the columns without any values.
...
UPDATE
Table
SET
A = CASE WHEN A!=NULL THEN A=NULL
B= CASE WHEN B!=NULL THEN B=NULL
C= CASE WHEN C!=NULL THEN C='U'
D= CASE WHEN D!=NULL THEN D=NULL ELSE END,
WHERE
where condition;
...
PS:: The column values are not same.
Your query was almost close.Below one should work,
update test_Data
set A = CASE WHEN A is not NULL THEN NULL END,
B = CASE WHEN B is not NULL THEN NULL END ,
C = CASE WHEN C is not NULL THEN NULL END,
D = CASE WHEN D is not NULL THEN NULL END,
E = CASE WHEN E = 'abc' THEN 'QWE' ELSE E END
where (A is not NULL or B is not NULL or C is not NULL or D is not null or E is not null)
UPDATE:
If any of the column has NOT NULL Constraint, then column has to be altered to take NULL.
alter table test_Data modify E null;
for demo with example refer DB fiddle link - https://dbfiddle.uk/?rdbms=oracle_18&fiddle=7f8bfc2f5edda71a9eb5af5ccb2065de

Conditional itab grouping alike HAVING clause in SQL

This is a follow-up question for this one but instead of aggregation I want to process groups based on some condition and cannot figure out the proper syntax for this. I need to exclude groups which contain documents with status "deleted", if at least one of the members of the group has this status.
I tried so far GROUP...WITHOUT MEMBERS, LOOP...FOR GROUPS, REDUCE and this is the solution I end up with
DATA(lt_valid_doc) = VALUE tt_struct(
FOR ls_valid IN VALUE tt_struct(
FOR GROUPS <group_key> OF <wa> IN lt_ilot
GROUP BY ( guid = <wa>-guid guid2 = <wa>-guid2 ) ASCENDING
LET not_deleted = REDUCE #( INIT valid TYPE t_ref_s_struct
FOR <m> IN GROUP <group_key>
NEXT valid = COND #(
WHEN valid IS NOT BOUND OR <m>-stat = 'I1040'
THEN REF #( <m> ) ELSE valid ) )
IN ( not_deleted->* ) )
WHERE ( status NE 'I1040' )
( ls_valid ) ).
 
However, this solution seems redundant to me (I1040 filter indicated twice). Is there any syntax that allows doing this in one statement (REDUCE, GROUP or whatever) without constructing nested table on-the-fly and filtering it like I am doing now?
If I use WHERE condition on all of the above statements (GROUP...WITHOUT MEMBERS, LOOP...FOR GROUPS and REDUCE) it only filters base lines for grouping not the groups itself. I need somewhat similar to HAVING in SQL.
UPDATE OK, here is real-life compilable example based on BSEG table. The task is find only unreveresed docs, i.e.to exclude all docs with reversed (XNEGP = true) lines.
TYPES: BEGIN OF t_s_bseg,
bukrs TYPE bseg-bukrs,
belnr TYPE bseg-belnr,
gjahr TYPE bseg-gjahr,
buzei TYPE bseg-buzei,
xnegp TYPE bseg-xnegp,
END OF t_s_bseg,
tt_bseg TYPE SORTED TABLE OF t_s_bseg WITH EMPTY KEY.
TYPES: t_ref_s_bseg TYPE REF TO t_s_bseg.
DATA(lt_valid_fi_doc) = VALUE tt_bseg(
FOR ls_valid IN VALUE tt_bseg(
FOR GROUPS <group_key> OF <wa> IN lt_bseg
GROUP BY ( bukrs = <wa>-bukrs belnr = <wa>-belnr gjahr = <wa>-belnr ) ASCENDING
LET not_reversed = REDUCE #( INIT valid TYPE t_ref_s_bseg
FOR <m> IN GROUP <group_key>
NEXT valid = COND #(
WHEN valid IS NOT BOUND OR <m>-xnegp = abap_true
THEN REF #( <m> ) ELSE valid ) )
IN ( not_reversed->* ) )
WHERE ( xnegp NE abap_true )
( ls_valid ) ).
Input lines
bukrs belnr gjahr buzei xnegp
1000 0100000001 2019 1
1000 0100000001 2019 2
1000 0100000003 2019 1
1000 0100000003 2019 2
1000 0100000004 2019 1
1000 0100000004 2019 2 X
Doc 0100000004 has reversed line so result should be
bukrs belnr gjahr buzei xnegp
1000 0100000001 2019
1000 0100000003 2019
Here's a solution which doesn't repeat the selection, but one question remains, is that really "better"?
The solution is based on generating an empty line if the group of lines contains one line with status 'I1040', instead of keeping the unwanted line. I'm not sure, but maybe another similar solution could keep the reference to the line (not_deleted), plus adding an auxiliary variable to know whether the reference is to keep or not. I found it more intuitive to use table indexes (INDEX INTO), but that might not work if tt_struct is a hashed table type.
I provide the code with an ABAP Unit Test so that you can quickly try it yourself.
CLASS ltc_main DEFINITION FOR TESTING
DURATION SHORT RISK LEVEL HARMLESS.
PRIVATE SECTION.
METHODS test FOR TESTING.
METHODS cut.
TYPES : BEGIN OF ty_struct,
guid TYPE string,
stat TYPE string,
END OF ty_struct,
tt_struct TYPE STANDARD TABLE OF ty_struct WITH EMPTY KEY,
t_ref_s_struct TYPE REF TO ty_struct.
DATA: lt_ilot TYPE tt_struct,
lt_valid_doc TYPE tt_struct.
ENDCLASS.
CLASS ltc_main IMPLEMENTATION.
METHOD cut.
lt_valid_doc = VALUE #(
FOR ls_valid IN VALUE tt_struct(
FOR GROUPS <group_key> OF <wa> IN lt_ilot
GROUP BY ( guid = <wa>-guid ) ASCENDING
LET x1 = REDUCE #(
INIT x2 = 0
FOR <m> IN GROUP <group_key> INDEX INTO x3
NEXT x2 = COND #(
WHEN <m>-stat = 'I1040' THEN -1
ELSE COND #( WHEN x2 <> 0 THEN x2 ELSE x3 ) ) )
IN ( COND #( WHEN x1 <> -1 THEN lt_ilot[ x1 ] ) ) )
WHERE ( table_line IS NOT INITIAL )
( ls_valid ) ).
ENDMETHOD.
METHOD test.
lt_ilot = VALUE #(
( guid = 'A' stat = 'I1000' )
( guid = 'A' stat = 'I1040' )
( guid = 'B' stat = 'I1020' )
( guid = 'C' stat = 'I1040' )
( guid = 'D' stat = 'I1040' )
( guid = 'D' stat = 'I1000' ) ).
cut( ).
cl_abap_unit_assert=>assert_equals( act = lt_valid_doc
exp = VALUE tt_struct( ( guid = 'B' stat = 'I1020' ) ) ).
ENDMETHOD.
ENDCLASS.
I really hope that was some kind of personal test case, and you do not use this coding in a productive environment. If I would have to understand what you want to achieve looking only at the coding, I would hate you ;).
The key to easily solve this problem is sorting the table so that the delete condition is always in the first row of the group you want to process:
Solution1
with output of unique list:
DATA: lt_bseg TYPE STANDARD TABLE OF t_s_bseg.
SORT lt_bseg BY belnr xnegp DESCENDING.
DELETE ADJACENT DUPLICATES FROM lt_bseg COMPARING belnr.
DELETE lt_bseg WHERE xnegp = abap_true.
Solution2
with output of a non-unique list:
DATA: lt_bseg TYPE STANDARD TABLE OF t_s_bseg,
lf_prev_belnr TYPE belnr,
lf_delete TYPE char1.
SORT lt_bseg BY belnr xnegp DESCENDING.
LOOP AT lt_bseg ASSIGNING FIELD-SYMBOL(<ls_bseg>).
IF <ls_bseg>-belnr <> lf_prev_belnr.
lf_delete = <ls_bseg>-xnegp.
lf_prev_belnr = <ls_bseg>-belnr.
ENDIF.
IF lf_delete = abap_true.
DELETE lt_bseg.
ENDIF.
ENDLOOP.
the following solution might not be the prettiest one, but its simple. I's easier to remove a whole group if one member meets a condition than to add a whole group if all of them fail the condtition. Just an idea.
TYPES : BEGIN OF ty_struct,
guid TYPE string,
stat TYPE string,
END OF ty_struct,
tt_struct TYPE STANDARD TABLE OF ty_struct WITH EMPTY KEY.
DATA(lt_ilot) = VALUE tt_struct(
( guid = 'A' stat = 'I1000' )
( guid = 'A' stat = 'I1040' )
( guid = 'B' stat = 'I1020' )
( guid = 'C' stat = 'I1040' )
( guid = 'D' stat = 'I1040' )
( guid = 'D' stat = 'I1000' )).
LOOP AT lt_ilot INTO DATA(ls_ilot) WHERE stat = 'I1040'.
DELETE lt_ilot WHERE guid = ls_ilot-guid.
ENDLOOP.

Access the previous record to compare the value in DAX POWER BI

I need to access the previous record of the DTH_REFER_PEDID column to make the IF comparison (DTH_REFER_PEDID-1 <> "A").
That is, I'm reading the index X, I need to compare with the index X-1
Addition_Stats = VAR Atendido_OV = PR_HIST_MOVIM_PEDID[OVITEM_Hist]
VAR linha_anterior2 = CALCULATE(values(PR_HIST_MOVIM_PEDID[STA_ITEM_PEDCL]);filter(PR_HIST_MOVIM_PEDID;EARLIER(PR_HIST_MOVIM_PEDID[DTH_REFER_PEDID])))
Return
if(PR_HIST_MOVIM_PEDID[DTH_REFER_PEDID].[Month]<PR_HIST_MOVIM_PEDID[DAT_MAIOR_PLANE].[Month];"Atraso mês ant";
if(PR_HIST_MOVIM_PEDID[STA_ITEM_PEDCL] = "A" && PR_HIST_MOVIM_PEDID[DTH_REFER_PEDID].[Day]<=PR_HIST_MOVIM_PEDID[DAT_MAIOR_PLANE].[Day];"Atendido no Prazo";
if((PR_HIST_MOVIM_PEDID[STA_ITEM_PEDCL]="P"||PR_HIST_MOVIM_PEDID[STA_ITEM_PEDCL]="L") && PR_HIST_MOVIM_PEDID[DTH_REFER_PEDID].[Day]<= PR_HIST_MOVIM_PEDID[DAT_MAIOR_PLANE].[Day];"Planejado no prazo";
if(PR_HIST_MOVIM_PEDID[STA_ITEM_PEDCL]<>"A" && PR_HIST_MOVIM_PEDID[DTH_REFER_PEDID].[Day]>PR_HIST_MOVIM_PEDID[DAT_MAIOR_PLANE].[Day];"Em atraso";
if(PR_HIST_MOVIM_PEDID[STA_ITEM_PEDCL] = "A"
&& linha_anterior2 <>"A"
&& PR_HIST_MOVIM_PEDID[DTH_REFER_PEDID].[Day]>PR_HIST_MOVIM_PEDID[DAT_MAIOR_PLANE].[Day];"Atend fora Prazo"
;IF((PR_HIST_MOVIM_PEDID[OVITEM_Hist]=Atendido_OV)&&(PR_HIST_MOVIM_PEDID[DTH_REFER_PEDID]>FIRSTDATE(PR_HIST_MOVIM_PEDID[DTH_REFER_PEDID].[Date]));"A retido";"NA")
)
)
)
)
)
//)
The error displayed is: A circular dependency has been detected: PR_HIST_MOVIM_PEDID [Addition_Stats].
How do I compare DTH_REFER_PEDID-1 <> "A"?
An easy way to work with previous or next records is:
Make sure your data is in a table with a primary key (=ID)
Make a query with all the fields as in your table and add one colum with ID+1. (or ID-1)
Make another query with the table and the query mentioned above and make a join between ID and ID+1 (or ID-1). Place all the fields of the table and the 1st query and you end up with all the values in 1 record. This way you can work with the previous or next values.

SELECT Statement within IF statement

I would like to get a different result to my select statement when a parameter is 0, 1 or 2. I am not very skilled in PLSQL so I am not sure if my code would give the expected result. If i run this code i get a "SQL statement ignored" on line 3.
BEGIN
IF (:PARTYPE = 1) THEN
SELECT * FROM x
WHERE to_date(date) >= (Select to_date(sysdate)from DNV.dual)
ELSE
SELECT * FROM x
WHERE to_date(date) <= (Select to_date(sysdate)from DNV.dual)
END IF;
END;
This is just a example of my SELECT statement. Later this statement will become longer and more complex but I think this shows which results I am trying to get.
Below is a copy of my entire code but because I am not allowed to show this it has become very unreadable:
BEGIN
IF (:PARTYPE = 1) THEN
Select table1.Column1
, table1.Column2
, table1.Column3
, table1.Column4
, table1.Column5
, table1.Column6
, table1.Column7
, table1.Column8
, table1.Column9
, table1.Column10
, table1.Column11
, table1.Column12
, (Select table2.ColumnX From x2 table2 Where somthing) as "something" From x1 table1
WHERE to_date(date) >= (Select to_date(sysdate)from DNV.dual)
Order by columnX
ELSE
Select table1.Column1
, table1.Column2
, table1.Column3
, table1.Column4
, table1.Column5
, table1.Column6
, table1.Column7
, table1.Column8
, table1.Column9
, table1.Column10
, table1.Column11
, table1.Column12
, (Select table2.ColumnX From x2 table2 Where somthing) as "something" From x1 table1
WHERE to_date(date) <= (Select to_date(sysdate)from DNV.dual)
Order by columnX
END IF;
END;
I have created some new code with which i am trying to learn how a case statement works. This might help me with the code above. Unfortunately this code also doesn't work but I think it explanes my situation better. In this excample i use a separate table with data i made up. In some cases user2 is null but user1 is always filled. I want to get all items where user2 equals the parameter but if user2 is null and user1 does equal the paramter i still need that item to apear.
Select t1.user1,
t1.user2
From table t1
Where (Case
When t1.user2 IS NULL Then t1.user1 in (:PARUSER)
ELSE t1.user2 in (:PARUSER)
End Case)
Since the relational operator of the where clause depends on the partype, you cannot do the traditional CASE statement charm here. I'll have to resort with this one:
SELECT * FROM x
WHERE (to_date(date) >= (Select to_date(sysdate)from DNV.dual) AND :PARTYPE = 1)
OR (to_date(date) <= (Select to_date(sysdate)from DNV.dual) AND :PARTYPE != 1)

Doctrine 2: how do you use a subquery column (in the SELECT clause)

I'm trying to do a simple select query with a subquery in the SELECT clause and have simply not found a way to do it. I've tried with both DQL and with the QueryBuilder, neither work. The code follows, please don't say I could just use a join, this is a simplified example just to illustrate the problem, I have legitimate use cases for subqueries.
// With QueryBuilder
$query = $qb->select(array('a',
'(SELECT at.addresstypeName
FROM e:Addresstype at
WHERE at.addresstypeId = a.addresstypeId
) AS addresstypeName'))
->from('e:Address', 'a')
->where('a.addressId = :addressId')
->setParameter('addressId', 1);
// With DQL
$dql = "SELECT a,
(SELECT at.addresstypeName
FROM e:Addresstype at
WHERE at.addresstypeId = a.addresstypeId
) AS addresstypeName
FROM e:Address a
WHERE a.addressId = :addressId";
$query = $em->createQuery($dql)->setParameter(':addressId', 1);
The following relationship is defined on the Address table:
/**
* #ORM\ManyToOne(targetEntity="Addresstype")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="addresstype_id", referencedColumnName="addresstype_id")
* })
*/
protected $addresstype;
In native SQL, the query would look like this:
SELECT
a.*,
(
SELECT at.addresstype_name
FROM addresstype at
WHERE at.addresstype_id = a.addresstype_id
) AS addresstype_name
FROM address a
WHERE a.address_id = 1
Any ideas?
$query = $qb->select('a')
->addSelect('(SELECT at.addresstypeName
FROM e:Addresstype at
WHERE at.addresstypeId = a.addresstypeId) AS addresstypeName'
)
->from('e:Address', 'a')
->where('a.addressId = :addressId')
->setParameter('addressId', 1);
For me subquery with doctrine works with this query :
$qb->select('e.field')
->addSelect('(SELECT count(mv.nm)
FROM Clt\Bundle\MyBundle\Entity\MV mv
LEFT JOIN Clt\Bundle\MyBundle\Entity\M ma WITH mv.nm=ma.nm
WHERE mv.ne=e.ne and ma.nm is null
) AS nm'
)
->from($this->_entityName, 'e')
->leftJoin('e.m', 'm')
->where($qb->expr()->eq('t.id'.$typeModule, $idElementModule));
Note that in the left join you must use WITH instead of ON...
I know this is an old question, but if you want, you could have used another query builder as your subquery:
$qb->select("a")
->addSelect("(" . $qb2->select("at.addresstypeName")
->from("e:Addresstype", "at")
->where("at.addresstypeId = a.addresstypeId")
->getDQL() . ") AS addresstypeName"
)
->from('e:Address', 'a')
->where('a.addressId = :addressId')
->setParameter('addressId', 1);
In my scenario what I needed was to look into a join and find an Id and use it as boolean, found 1 otherwise 0, then applying this to orderBy. DQL expressions worked only when combined with Where clause, which wasn't my case. So, a DQL subselect saved me.
Adapted more or less to your scenario, it would look like this:
// With QueryBuilder
// In AddressRepository
// Where one address may belong to several addressTypes
public function getWithType($addressType){
$qb = $this->createQueryBuilder('a1');
$qb->addSelect('a1.someField', 'a1.otherField')
$qb->addSelect(
'(SELECT at.addressTypeName
FROM App\Entity\Address a2
JOIN a2.addressType at
WHERE at.id = '.$addressType.' AND a2.id = a1.id
) AS addressTypeName')
//The rest part of the query
}