我想知道是否可以使用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个日期销售数量增加的产品。
例如,查找2019年3月1日销售编号大于2019年1月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
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
您可以作为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)
);