简体   繁体   中英

Query on MAX on date column, and COUNT of another column

I performed the following query with cte's, but I was wondering if there was a simpler way of writing the code, maybe with subqueries? I'm retrieving everything from one table SALES, but I'm using 3 columns: AgentID, SaleDate, and 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;

Try this:

 SELECT 
    saledate,
    AGENTID, 
    count(orderid) over(partition by AGENTID order by saledate)
 FROM SALES
 group by  
    saledate,
    AGENTID

It looks to me like you're just trying to get the total number of sales per agent as well as the date of his or her most recent sale? If I understand your structure correctly (and I may not), then it seems pretty straightforward. I'm guessing orderid is the primary key of SALES ?

SELECT agentid, MAX(saledate) AS saledate -- Most recent sale date
     , COUNT(orderid) AS countsales -- total sales
  FROM sales
 GROUP BY agentid;

There does not seem to be any need for CTEs or subqueries here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM