I am using one table in SQL Server.
This is how the table is displayed originally:
| ItemNo | StoreNo | DemandYr1 | DemandYr2 | DemandYr3 |
| ------------ | ------------ | ------------ | ------------ | ------------ |
| 1 | AA | 2 | 3 | 0 |
| 1 | BB | 5 | 1 | 2 |
| 5 | BB | 5 | 5 | 5 |
| 5 | CC | 0 | 0 | 6 |
| 3 | AA | 2 | 1 | 4 |
| 3 | BB | 1 | 0 | 3 |
| 3 | CC | 2 | 2 | 2 |
After using this query,
select itemno, storeno, sum(DemandYr1 + DemandYr2 + DemandYr3) as SumDemand
from ExTable
group by itemno, storeno
order by itemno asc
I have gotten the table to this:
ItemNo | StoreNo | SumDemand |
---|---|---|
1 | AA | 5 |
1 | BB | 8 |
5 | BB | 15 |
5 | CC | 6 |
3 | AA | 7 |
3 | BB | 4 |
3 | CC | 6 |
Now, my desired result is to only show the storeno with the highest SumDemand for each ItemNo in a table like this:
ItemNo | StoreNo | SumDemand |
---|---|---|
1 | BB | 8 |
5 | BB | 6 |
3 | CC | 6 |
Since the SumDemand column is not part of the original table and was added by me, I am not sure how to query it to only show the greatest SumDemand for each ItemNo. I understand that if two StoreNo's have the same SumDemand there will be duplicates, that is fine.
** If possible, I would also like to omit any results that = 0. Ex: If an Item No has 0 SumDemand at all stores, I would like to delete. (If this is not possible that is also fine) **
2条答案
按热度按时间t9eec4r01#
You can add a row_number to your select in combination with a CTE.
But you should avoid adding spaces in your column names as the must all be escaped
Fiddle
bf1o4zei2#
The way you approach this is to use a windowed count; also here the addition is moved to a cross-apply so it can be re-used.