Skip to content
Advertisement

Select data from date range in DB2 SQL

I have a trouble trying get a data in DB2 SQL. I have a table Name StProdMoves and it holds data like this

ProdName | Status  | Brand | Type  | Date(Numeric)
----------+---------+-------+-------+-----------
ORANGE    | 10      |  SBR  |  IN   | 20181217105640
APPLE     | 10      |  SBR  |  IN   | 20181220143520
GARLIC    | 20      |  SBR  |  IN   | 20190107095740
APPLE     | 20      |  JUM  |  OUT  | 20190107121050
ORANGE    | 20      |  AUR  |  OUT  | 20190110164530
ORANGE    | 20      |  AUR  |  IN   | 20190110000000
GARLIC    | 10      |  SBR  |  OUT  | 20190211000000

Now what is the query if I want to select sales data between two dates from a date range?

For example, I want to select the products that stayed in the range 31/12/2018 and 07/01/2019 and brand=SBR and Status=10.

Edit: I trying get the data using this query, but not all products selected show in that range of dates, then show a result like this:

SELECT * FROM StProdMoves WHERE DATE(TO_DATE(SUBSTR(DIGITS(Date), 1, 8), 'YYYYMMDD')) BETWEEN '31/12/2018' AND '07/01/2019' AND Brand='SBR' AND Status=10

Later as ProducName, Status, Brand, DateIn and DateOut where show all products exist in this date or range of date, like this

 ProdName | Status  | Brand |  DateIn  | DateOut
----------+---------+-------+-------+-----------
ORANGE    | 10      |  SBR  | 20181217 | ---
APPLE     | 10      |  SBR  | 20181220 | ---
PEAR      | 10      |  SBR  | 20181120 | 20190106

Advertisement

Answer

If you have your dates as Numeric values in such a format as you provided, the most efficient way to query your table with DATE parameters should be like below:

select *
from (
          select 20181217105640 from sysibm.sysdummy1
union all select 20181220143520 from sysibm.sysdummy1
) StProdMoves (DateNumeric)
where 
    DateNumeric > bigint(varchar_format(DATE('2018-12-18'), 'YYYYMMDDHH24MISS'))
and DateNumeric < bigint(varchar_format(DATE('2019-01-06'), 'YYYYMMDDHH24MISS'));

We translate the Date input parameters to the Numeric timestamp representation of your data in such a way.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement