我用cte&s进行了以下查询,但我想知道是否有更简单的编写代码的方法,可能是子查询?我从一个表SALES中检索所有内容,但我使用了3列:AgentID,SaleDate和OrderID。
WITH RECENT_SALE AS(
SELECT AGENTID,(
SALEDATE,
ROW_NUMBER() OVER (PARTITION BY AGENTID ORDER BY SALEDATE DESC) AS RN
FROM SALES
)
,
COUNT_SALE AS (
SELECT AGENTID,
COUNT(ORDERID) AS COUNTORDERS
FROM SALES
)
SELECT RECENT_SALE.MRN,
SALEDATE,
COUNTORDERS
FROM RECENT_SALE
INNER JOIN COUNT_SALE ON RECENT_SALE.AGENTID = COUNT_SALE.AGENTID;
答案 0 :(得分:0)
试试这个:
SELECT
saledate,
AGENTID,
count(orderid) over(partition by AGENTID order by saledate)
FROM SALES
group by
saledate,
AGENTID
答案 1 :(得分:0)
在我看来,您只是想了解每个代理商的销售总数以及他或她最近的销售日期?如果我正确理解你的结构(我可能没有),那么它似乎非常简单。我猜orderid
是SALES
的主键?
SELECT agentid, MAX(saledate) AS saledate -- Most recent sale date
, COUNT(orderid) AS countsales -- total sales
FROM sales
GROUP BY agentid;
这里似乎没有任何CTE或子查询的需要。