CREATE TABLE #ITEMS1 (
Itemid int,
ORDERDate date,
Price money)
INSERT INTO #ITEMS1(Itemid, ORDERDATE, PRICE)
VALUES
(1,'1/1/2018',$700),
(1,'2/1/2018',$150),
(1,'3/1/2018',$200),
(1,'4/1/2018',$950),
(1,'5/1/2018',$300),
(2,'7/1/2017',$350),
(2,'8/1/2017',$400),
(2,'9/1/2017',$450),
(2,'10/1/2017',$500),
(3,'12/31/2017',$550),
(3,'1/1/2018',$650),
(1,'1/2/2018',$700),
(1,'1/3/2018',$250)
按项目获取价格总和,但忽略每个项目最近一个月的订单。
SELECT ITEMid, SUM(Price)
FROM #ITEMS1 I
WHERE
Month(ORDERDATE) NOT IN (SELECT max(Month(ORDERDATE)) FROM #ITEMS1 I2 WHERE I2.Itemid=I.Itemid)
GROUP BY Itemid
答案 0 :(得分:0)
可以使用下面的CASE
语句尝试忽略每个组的max(Date)
SELECT ITEMid,
CASE WHEN DATE<>
MAX(DATE)
THEN SUM(PRICE)
ELSE SUM(0)
END CASE FROM
TABLE
GROUP BY ITEMID;
答案 1 :(得分:0)
假设您每月只有一个订单(例如您的示例),则可以执行以下操作:
SELECT ITEMid, SUM(Price)
FROM #ITEMS1 I
WHERE ORDERDATE < (SELECT MAX(I2.ORDERDATE)
FROM #ITEMS I2
WHERE I2.Itemid = I.Itemid
)
GROUP BY Itemid;
这很容易适应上个月。但是,确切的语法取决于您使用的数据库。
编辑:
在SQL Server中,每月使用的语法为:
SELECT ITEMid, SUM(Price)
FROM #ITEMS1 I
WHERE ORDERDATE < (SELECT MAX(I2.ORDERDATE)
FROM #ITEMS I2
WHERE I2.Itemid = I.Itemid AND
EOMONTH(I2.ORDERDATE) = EOMONTH(I.ORDERDATE)
)
GROUP BY Itemid;
答案 2 :(得分:0)
SELECT Itemid,min(ORDERDate)'Mindate',Max(orderdate)'maxdate' 进入#temp1 来自#ITEMS1 按商品ID分组
SELECT ITEMid,SUM(价格) 来自#ITEMS1我 哪里 Month(ORDERDATE)NOT IN(从#temp1 t WHERE t.itemid = I.itemid处选择(Month(maxdate)) 按商品ID分组