CASE expression in WHERE clause Postgresql - postgresql

I have been struggling to figure out how to put a CASE expression in the WHERE clause using PostgreSQL. I need to convert the string to a date (as seen in line 3). This works fine. When I try to pull CURRENT_DATE in the WHERE clause I run into errors. Is this the best way to do this? Any suggestions would be very much welcomed.
SELECT
CASE WHEN
multi_app_documentation.nsma1_code = 'DATE' THEN TO_DATE(multi_app_documentation.nsma1_ans, 'MMDDYYYY') END AS "Procedure Date",
' ' AS "Case Confirmation Number",
ip_visit_1.ipv1_firstname AS "Patient First",
ip_visit_1.ipv1_lastname AS "Patient Last",
visit.visit_sex AS "Patient Gender",
TO_CHAR(visit.visit_date_of_birth, 'MM/DD/YYYY') AS "DOB",
visit.visit_id AS "Account Number",
visit.visit_mr_num AS "MRN",
' ' AS "Module",
' ' AS "Signed off DT",
CASE WHEN
multi_app_documentation.nsma1_code = 'CRNA' THEN multi_app_documentation.nsma1_ans END AS "Primary CRNA",
' ' AS "Secondary CRNA",
' ' AS "Primary Anesthesiologist",
' ' AS "Secondary Anesthesiologist",
' ' AS "Canceled Yes/No"
FROM
multi_app_documentation
INNER JOIN ip_visit_1 ON multi_app_documentation.nsma1_patnum = ip_visit_1.ipv1_num
INNER JOIN visit ON ip_visit_1.ipv1_num = visit.visit_id
WHERE
CASE
WHEN ( multi_app_documentation.nsma1_code = 'DATE' AND TO_DATE( multi_app_documentation.nsma1_ans, 'MMDDYYYY' ) = CURRENT_DATE END )
AND multi_app_documentation.nsma1_ans IS NOT NULL
ORDER BY
ip_visit_1.ipv1_lastname ASC

Your parentheses are unbalanced. Also, you don't even need a CASE expression in the WHERE clause. Use this version:
WHERE
multi_app_documentation.nsma1_code = 'DATE' AND
TO_DATE(multi_app_documentation.nsma1_ans, 'MMDDYYYY') = CURRENT_DATE
In addition, it is undesirable to store text dates in the nsma1_ans column. It would be better to use a bona-fide date column. If you must store the dates as text, then at least use the format YYYY-MM-DD, which then could simply be cast to date using nsma1_ans::date.

Related

why do i have a date error in my sql query?

I am doing an SQL SELECT query but I have the error message:
"SQL Error [22007]: [SQL0181] A value of date, time, or timestamp
string is incorrect."
Here is my request:
SELECT *
FROM ROXDTA400.STKF0300 A
JOIN ROXDTA400.TABJ00141 B ON A.STNSIT = B.CDSITE
WHERE ( A.STNLIB <> '-- Trémie --'
AND A.STNSIT <> 40
AND DATE(LEFT(STNDAV,4) || '-' || substr(STNDAV,5,2) || '-' || RIGHT(STNDAV,2))
BETWEEN DATE('2019-01-01') AND DATE('2019-01-04') );
The problem seems to come from the date created with the STNDAV field, because if I replace with for example DATE ('2019-01-03'), it works.
DATE (LEFT (STNDAV, 4) || '-' || substr (STNDAV, 5,2) || '-' || RIGHT (STNDAV, 2)) Gives me the correct date format.
Where would the problem come from?
thank you,
Ensure that dates stored in STNDAV are valid. I mean, check there is any invalid date such as February 30th or '99999999'. If the source is an IBM i (iSeries or AS/400), it will be faster if you avoid functions in the WHERE portion, so STNDAV BETWEEN '20190101' AND '20190104' will perform better.

Correct statement for UNION ALL with three or more selects

I have the following situation:
I have a script consisting of 6 selects joined by "UNION ALL".
From the CLP DB2 console, this script fails. Curiously, each query independently work, and even come to work if grouped in pairs. However, when I try with three or more, it fails.
So, my question is: is there is a limit for more that one UNION ALL?
My environment is:
Client. DB2 Connect server 10.1
zOS 390 (no idea what is the DB2 version on that side)
AIX 7.1
The query is like this (but three times )
SELECT
,'GG'
,varchar(right( '000000000000000' || rtrim(ltrim(eeee.zzzz)), 15), 15)
,substr(char(right('**********'||char(left(replace(eeee.yyyy,' ','*')||'**********',10),10),10),10),1,7)
,eeee.kkkkk
,eeee.hhhhhh
,CASE WHEN hhhhhh='A5 ' THEN 'ARS' WHEN hhhhhh='A6 ' THEN 'AUD' WHEN hhhhhh='B5 ' THEN 'BRL' WHEN hhhhhh='U1 ' THEN 'GBP' WHEN hhhhhh='B9 ' THEN 'BND' WHEN hhhhhh='B6 ' THEN 'BNG' WHEN hhhhhh='C1 ' THEN 'CAD' WHEN hhhhhh='C3 ' THEN 'CLP' WHEN hhhhhh='C4 ' THEN 'CNY' WHEN hhhhhh='C5 ' THEN 'COP' WHEN hhhhhh='C7 ' THEN 'CRC' WHEN hhhhhh='L5 ' THEN 'HRK' WHEN hhhhhh='C9 ' THEN 'CYP' WHEN hhhhhh='X0 ' THEN 'CZK' WHEN hhhhhh='D0 ' THEN 'DKK' WHEN hhhhhh='D1 ' THEN 'DOP' WHEN hhhhhh='U0 ' THEN 'EGP' WHEN hhhhhh='E3 ' THEN 'EUR' WHEN hhhhhh='G5 ' THEN 'GTQ' WHEN hhhhhh='H0 ' THEN 'HTG' WHEN hhhhhh='H3 ' THEN 'HUF' WHEN hhhhhh='I1 ' THEN 'INR' WHEN hhhhhh='I2 ' THEN 'IDR' WHEN hhhhhh='K2 ' THEN 'WON' WHEN hhhhhh='L6 ' THEN 'LVL' WHEN hhhhhh='L7 ' THEN 'LTL' WHEN hhhhhh='M2 ' THEN 'MYR' WHEN hhhhhh='M6 ' THEN 'MXN' WHEN hhhhhh='I8 ' THEN 'ILS' WHEN hhhhhh='N2 ' THEN 'NZD' WHEN hhhhhh='N4 ' THEN 'NIO' WHEN hhhhhh='N6 ' THEN 'NOK' WHEN hhhhhh='T4 ' THEN 'XPF' WHEN hhhhhh='P0 ' THEN 'PKR' WHEN hhhhhh='P1 ' THEN 'PAB' WHEN hhhhhh='P3 ' THEN 'PEN' WHEN hhhhhh='P4 ' THEN 'PHP' WHEN hhhhhh='P5 ' THEN 'PLN' WHEN hhhhhh='R2 ' THEN 'RON' WHEN hhhhhh='U3 ' THEN 'RUB' WHEN hhhhhh='S0 ' THEN 'SAR' WHEN hhhhhh='R6 ' THEN 'RSD' WHEN hhhhhh='S2 ' THEN 'SGD' WHEN hhhhhh='K5 ' THEN 'SKK' WHEN hhhhhh='S4 ' THEN 'ZAR' WHEN hhhhhh='C2 ' THEN 'LKR' WHEN hhhhhh='S8 ' THEN 'SEK' WHEN hhhhhh='S9 ' THEN 'CHF' WHEN hhhhhh='T2 ' THEN 'THB' WHEN hhhhhh='T6 ' THEN 'TRL' WHEN hhhhhh='U4 ' THEN 'USD' WHEN hhhhhh='U6 ' THEN 'UAH' WHEN hhhhhh='U5 ' THEN 'AED' WHEN hhhhhh='U2 ' THEN 'UYU' WHEN hhhhhh='V0 ' THEN 'VEB' WHEN hhhhhh='V1 ' THEN 'VND' WHEN hhhhhh='J1 ' THEN 'JPY' ELSE '###' END
, case when eeee.FCRCIDF='Y' then 1 else 0 end
,
CASE
WHEN SUBSTR(eeee.yyyy,7,1) = 'X' THEN 'X'
WHEN SUBSTR(eeee.yyyy,4,2) = 'O' THEN 'O'
WHEN SUBSTR(eeee.yyyy,4,2) = 'C' THEN 'C'
WHEN SUBSTR(eeee.yyyy,4,2) = 'R' THEN 'R'
WHEN eeee.lll = 'F' THEN 'F'
WHEN eeee.ppp <> '' THEN 'D'
WHEN eeee.rrr = 0 THEN '0'
WHEN eeee.rrr <> eeee.ACINTOT THEN 'P'
WHEN eeee.rrr = eeee.ACINTOT THEN '1'
ELSE '*'
END
,1
,eeee.DCINISS
,0
from (SELECT ori.*,oric.tttt FROM www.SK1V01_CUSTOMER ori left OUTER JOIN www.SK1V01A_CUSTCUF oric
ON ori.bbbb=oric.bbbb and ori.ICUSCNO=oric.ICUSCNO ) as aaaa
,www.SK1V02_OPENBILL eeee,www.SK1V41_OPENBILL kkkk
where aaaa.bbbb=eeee.bbbb
and aaaa.cagllic=eeee.cagllic
and aaaa.icuscno=eeee.icuscno
Without the entire statement its pretty hard to determine exact reasons. An given that just one portion is so long & poorly formatted, I'm not sure we'd want to dig through it all. But I can suggest a few approaches that may help resolve your problem.
Simplest part first. In practically any computer language, well formatted code helps you see the structure of what's going on. It may also help you spot the differences between your queries. (Perhaps you know this, & your code merely lost its formatting when you tried to post it.)
When trying to UNION multiple complex queries, it's not uncommon to have column inconsistencies among the queries. You might have missing or extra columns, or columns out of order. But it's possible some of your column expressions are evaluating to different types. You might want to cast() those expressions, or use type conversion functions, just to be sure.
There's so much going on here. Try testing with a version where you comment out large chunks of code, same on each major subquery, until you find which part is causing the problem.
You have a ridiculously long CASE expression on hhhhhh. Why don't you put these value pairs into a lookup table that you can join to.
Try using a module approach, just as you should when writing a large program. You could create a view for each of the major queries, then UNION them together. (Some developers use layers of views like layers of modular code).
Metadata about your views is available in the database catalog views. This means you could write a query to compare the attributes of the columns in your set of union views.

how to replace comma in List of string in Jasper report

I have create one report with list of the string. The string got value parameter TO.REFOS_STATUS_CODE in ('10','ZZ','11','12','13'). i want to replace "," with ".". i have try the solution with my expression but it does'nt work.
The parameter expression is $P{refos_status}.equalsIgnoreCase("0") ?" ": " TO.REFOS_STATUS_CODE IN ( " +$P{refos_status}.replace( ',', '.' )+ ")".
Anyone know how to do that?
This is my query:
SELECT
TO.REFOS_STATUS_DESC_RPT ,
SUM(US.ENFUS_TOTAL_OFF_ACT) TOTAL
FROM TENF_RPT_UNSETTLE_SUMMACT US
INNER JOIN TREF_BRANCH B ON B.REFBR_BRANCH_ID = US.ENFUS_BRANCH
INNER JOIN TREF_STATE ST ON B.REFBR_STATE_CODE = ST.REFST_STATE_CODE
INNER JOIN TREF_OFFENCE_STATUS TO ON US.ENFUS_OFF_ACT =TO.REFOS_STATUS_CODE
WHERE
$P!{refos_status_1}
GROUP BY
TO.REFOS_STATUS_CODE,
TO.REFOS_STATUS_DESC_RPT
ORDER BY
TO.REFOS_STATUS_CODE,
TO.REFOS_STATUS_DESC_RPT

PGSQL - Joining two tables on complicated condition

I got stuck during database migration on PostgreSQL and need your help.
I have two tables that I need to join: drzewa_mateczne.migracja (data I need to migrate) and ibl_as.t_adres_lesny (dictionary I need to join with migracja).
I need to join them on replace(drzewa_mateczne.migracja.adresy_lesne, ' ', '') = replace(ibl_as.t_adres_lesny.adres, ' ', ''). However my data is not very regular, so I want to join it on first good match with the dictionary.
I've created the following query:
select
count(*)
from
drzewa_mateczne.migracja a
where
length(a.adresy_lesne) > 0
and replace(a.adresy_lesne, ' ', '') = (select substr(replace(al.adres, ' ', ''), 1, length(replace(a.adresy_lesne, ' ', ''))) from ibl_as.t_adres_lesny al limit 1)
The query doesn't return any rows.
It does successfully join empty rows if ran without
length(a.adresy_lesne) > 0
The two following queries return rows (as expected):
select replace(adres, ' ', '')
from ibl_as.t_adres_lesny
where substr(replace(adres, ' ', ''), 1, 16) = '16-15-1-13-180-c'
limit 1
select replace(adresy_lesne, ' ', ''), length(replace(adresy_lesne, ' ', ''))
from drzewa_mateczne.migracja
where replace(adresy_lesne, ' ', '') = '16-15-1-13-180-c'
I'm suspecting that there might be a problem in sub-query inside the 'where' clause in my query. If you guys could help me resolve this issue, or at least point me in the right direction, I'd be very greatful.
Thanks in advance,
Jan
You can largely simplify to:
SELECT count(*)
FROM drzewa_mateczne.migracja a
WHERE a.adresy_lesne <> ''
AND EXISTS (
SELECT 1 FROM ibl_as.t_adres_lesny al
WHERE replace(al.adres, ' ', '')
LIKE (replace(a.adresy_lesne, ' ', '') || '%')
)
a.adresy_lesne <> '' does the same as length(a.adresy_lesne) > 0, just faster.
Replace the correlated subquery with an EXISTS semi-join (to get only one match per row).
Replace the complex string construction with a simple LIKE expression.
More information on pattern matching and index support in these related answers:
PostgreSQL LIKE query performance variations
Difference between LIKE and ~ in Postgres
speeding up wildcard text lookups
What you're basically telling the database to do is to get you the count of rows from drzewa_mateczne.migracja that have a non-empty adresy_lesne field that is a prefix of the adres field of a semi-random ibl_as.t_adres_lesny row...
Lose the "limit 1" in the subquery and substitute the "=" with "in" and see if that is what you wanted...

TSQL -- Inserting Dates Into Dynamic SQL

Consider the following TSQL:
SET #WhereClause1 = 'where a.Date > ' + #InvoiceDate
I get a date/string conversion error. #InvoiceDate is a datetime variable. What is the right syntax?
This might work.
SET #WhereClause1 = 'where a.Date > ''' + convert(varchar, #InvoiceDate) + ''''
although an error will be raised if the value is null.
This will work:
SET #WhereClause1 = 'where a.Date > ''' + cast(#InvoiceDate as varchar(100)) + ''''
Since your composing query as a string first, then I think you need to convert #InvoiceDate to a string with something like this. http://www.databasejournal.com/features/mssql/article.php/10894_2197931_1/Working-with-SQL-Server-DateTime-Variables-Part-Two---Displaying-Dates-and-Times-in-Different-Formats.htm
... and you will probably need to enclose date strings in quotes.
It would probably actually be better to construct the date string in the calling routine because you should be checking there for null values and maybe other validations.
EXEC sp_executesql N'SELECT * FROM Orders WHERE a.Date > #date',
N'#date datetime',
#date = #InvoiceDate