我想知道是否可以使用SQL查询来做到这一点。 我有一个名为“数据”的表,其中包含产品名称,日期和销售编号。
我的桌子看起来像这样:
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
我想设置一个SQL查询来查找在某些2个日期销售量增加的产品。
例如查找所有在3/1/2019的销售编号大于1/1/2019的产品 并且应该返回橙色和草莓。
我是编程领域的新手,我们将为您提供帮助。 预先感谢!
答案 0 :(得分:1)
您可以尝试使用相关子查询
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
答案 1 :(得分: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
答案 2 :(得分:0)
您可以以JOIN
的身份进行此操作,但我建议:
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';
注意:您应该为日期常数使用标准日期格式-'2019-01-03'
或'2019-03-01
',具体取决于您的意思。
您也可以使用聚合来完成此操作:
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)
);