2

I am wondering if I can do this using SQL query. I have a table called "data" which contains the product name, date and sale number.

my table look like this:

Product         date       Sale

apple           1/1/2019   5
apple           2/1/2019   4
apple           3/1/2019   3
apple           4/1/2019   2
apple           5/1/2019   1
orange          1/1/2019   1
orange          2/1/2019   2
orange          3/1/2019   3
orange          4/1/2019   4
orange          5/1/2019   5
pear            1/1/2019   6
pear            2/1/2019   4
pear            3/1/2019   3
pear            4/1/2019   2
pear            5/1/2019   5
strawberry      1/1/2019   6
strawberry      2/1/2019   3 
strawberry      3/1/2019   7  
strawberry      4/1/2019   4
strawberry      5/1/2019   2

I would like to set a SQL query to find the product(s) which have increase sale number at certain 2 dates.

e.g. find all product which the sale number on 3/1/2019 is greater then 1/1/2019 and it should return orange and strawberry.

I am quite new into the programming world and any help is appreciated. Thanks in advance!

jarlh
  • 42,561
  • 8
  • 45
  • 63
Max Cheung
  • 176
  • 3
  • 13

3 Answers3

1

You can try using correlated subquery

DEMO

select name,sdate,amount from data a where exists 
  (
   select 1 from data b where a.name=b.name and b.sdate in ('1/1/2019','3/1/2019') and b.amount>a.amount
   and a.sdate<b.sdate
  ) 
and a.sdate in ('1/1/2019','3/1/2019')

OUTPUT:

name        sdate               amount
orange      01/01/2019 00:00:00   1
strawberry  01/01/2019 00:00:00   6
Fahmi
  • 37,315
  • 5
  • 22
  • 31
  • thanks for your answer. I dont quite understand what is t1 a and t1 b. I will check the correlated subquery out and study a bit on your suggested code. – Max Cheung Feb 11 '19 at 07:06
  • In what sense is one date greater than another (with the obvious exception of my birthday)? – Strawberry Feb 11 '19 at 08:29
0
DECLARE @FasatDate Date ='3-1-2019'
DECLARE @SecondDate Date ='1-1-2019'

SELECT T1.Product,T1.[date] FasatDate,T1.Sale FasatDateSale,T2.[date] SecondDate,T2.Sale SecondDateSale FROM (
SELECT * FROM DATA AS [DA]
WHERE [DA].[date]=@FasatDate) T1

INNER JOIN  (
SELECT * FROM DATA AS [DA]
WHERE [DA].[date]=@SecondDate)T2
on
t1.Product = t2.Product AND t1.Sale>t2.Sale
0

You can do this as a JOIN, but I would recommend:

select t1.*, t2.sales
from t t1 join
     t t2
     on t2.product = t1.product and
        t2.sales > t1.sales
where t1.date = '1/1/2019'
      t2.date = '3/1/2019';

Note: You should use standard date formats for your date constants -- either '2019-01-03' or '2019-03-01' depending on what you mean.

You can also do this using aggregation:

select product
from t
where t.date in ('1/1/2019', '3/1/2019')
group by product
having (sum(case when t.date = '1/1/2019' then sales end) <
        sum(case when t.date = '3/1/2019' then sales end)
       );
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786