Sql server TSQL-分组依据和总和未分组列

Sql server TSQL-分组依据和总和未分组列,sql-server,tsql,group-by,Sql Server,Tsql,Group By,我正面临某种问题。我有一个带有列的“价格”表——ProductId、ShopId、日期、价格。 表包含不同商店产品的价格历史记录。每种产品都可以在不同的商店购买,价格和日期也不同 我想得到所有商店每种产品的最新价格的总和 | ProductId | ShopId | Date | Price | |:---------:|:------:|:----------:|:------:| | 1 | 1 | 2020.11.10 | 100 | |

我正面临某种问题。我有一个带有列的“价格”表——ProductId、ShopId、日期、价格。 表包含不同商店产品的价格历史记录。每种产品都可以在不同的商店购买,价格和日期也不同

我想得到所有商店每种产品的最新价格的总和

| ProductId | ShopId |   Date     |  Price |
|:---------:|:------:|:----------:|:------:|
|     1     |   1    | 2020.11.10 |  100   |
|     1     |   2    | 2020.11.10 |  120   |
|     2     |   3    | 2020.11.10 |  200   |
|     3     |   3    | 2020.10.05 |  170   |
|     4     |   4    | 2020.11.10 |  200   |
|     4     |   4    | 2019.09.05 |  250   |
我想要得到的输出是(输出中可以包括ShopId和日期):

我有以下疑问:

SELECT ProductId, ShopId, MAX(Date) as MaxDate
FROM Prices
GROUP BY ShopId, ProductId
ORDER BY ProductId

使用窗口功能识别最新日期并过滤掉旧记录

;With dat
As (SELECT ProductId, ShopId, Date , Price
         , row_number() over partition by prodictid, date order by date desc)r
FROM Prices)

Select Productid
           , sum(price) Pricesum
From dat
Where rid=1
Group by productid;

我找到了解决办法,不是最快的,而是有效的

 select st.ProductId, SUM(st.Price)
 from Prices as p1 
 cross apply 
     (
        select ProductId, ShopId, MAX(Date) as MaxDate
        from Prices
        group by ShopId, ProductId
     ) as p2
 where p2.MaxDate = p1.Dt 
    and p2.Shopid = p1.ShopId
    and p2.ProductId = p1.ProductId
 group by p1.ProductId 
 order by p1.ProductId

在您的情况下,
密集等级
窗口功能可以帮助您。如果两行或更多行在同一分区中具有相同的秩值,则这些行中的每一行都将接收相同的秩

WITH LatestPricesCTE AS
(
    SELECT *, DENSE_RANK() OVER (PARTITION BY ProductID ORDER BY Date DESC) Rank
    FROM Prices
)
SELECT ProductId, SUM(Price) PriceSum
FROM LatestPricesCTE
WHERE Rank = 1
GROUP BY ProductId
有关更多信息:

获取/然后
求和
。我认为您不想在此处按
日期进行划分。请在您的答案中添加一些解释,以便其他人可以从中学习
WITH LatestPricesCTE AS
(
    SELECT *, DENSE_RANK() OVER (PARTITION BY ProductID ORDER BY Date DESC) Rank
    FROM Prices
)
SELECT ProductId, SUM(Price) PriceSum
FROM LatestPricesCTE
WHERE Rank = 1
GROUP BY ProductId