我正在尝试运行一个查询,查找过去x年没有购买任何东西的客户。我不确定是使用循环,还是使用BETWEEN关键字。
如果您需要查看表格,请告诉我,谢谢。
-- Find out the information of the customers who have not purchased anything in the
--last couple of years. Give the number of years (e.g., 1,2,3,4).
create procedure purchaseYear(@year int)
AS
select *
from customer
where CID IN(
select CID from item
where ItemNum IN (
select ItemNum from sale
where year(Comp_Date) = Between year(getdate()) AND @year))
答案 0 :(得分:0)
像这样的东西
Declare @Year int = 7
Select A.*
From Customer A
Join (Select CID
From Item
Group By CID
Having max(Comp_Date)<=DateAdd(YY,-@Year,cast(GetDate() as date))
) B
on A.CID=B.CID
答案 1 :(得分:0)
看看是否有效。
BEGIN
set @mulai=_tanggalmulai;
set @akhir=_tanggalakhir;
IF @mulai <> '' && @akhir <> '' THEN
SET @setWhere=' and date(created_at) between STR_TO_DATE(@mulai,''%d/%m/%Y'') and STR_TO_DATE(@akhir,''%d/%m/%Y'')';
ELSEIF @mulai <> '' && @akhir = '' THEN
SET @setWhere=' and date(created_at) > NOW()';
ELSEIF @mulai = '' && @akhir <> '' THEN
SET @setWhere=' and date(created_at) < NOW()';
ELSE
SET @setWhere=' ';
END IF;
SET @qry=CONCAT('SELECT id,norekammedik,nama,jeniskelamin,tempatlahir,nohp,alamat,DATE_FORMAT(tanggallahir,''%d/%m/%Y'') as tanggallahir,DATE_FORMAT(created_at,''%d/%m/%Y'') as created_at FROM pasien where 1=1',@setWhere,' ORDER BY id DESC');
PREPARE stmt FROM @qry;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
答案 2 :(得分:0)
如果您将问题改为&#34;我想找到最近购买时间超过x年的公司&#34;答案应该清楚。
; with companyAndLastPurchaseAge as (
Select companyId, max(DateDiff(y, saledate, getdate())) YearsAgo
From sale
Group by companyId
)
select cid.*
From cid
Left join companyAndLastPurchaseYear cp
On cp.CompanyId = cid.companyId and yearsago < x
Where cp.companyid is null;
答案 3 :(得分:0)
create procedure purchaseYear(@year int)
AS
select *
from customer as c
where not exists(
Select item.CID from sale
inner join item on item.ItemNum=sale.ItemNum
where item.CID=c.CID and datediff(year,Comp_Date,GETDATE()) Between 0 AND @year
)