SQL Server Return Average based on Per Item in each line

5hcedyr0  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(121)

I have Data as follows from a select Statement from ItemDetails Table:

INPUT [Same Ref]:
| ItemNo | ItemValue | Ref |
| ------------ | ------------ | ------------ |
| ITM001 | 81 | A1 |
| ITM002 | 45 | B1 |
| ITM001 | 81 | A1 |

Expected OUTPUT [Same Ref - Do AVG]:

ItemNoItemValueRef
ITM00140.50A1
ITM00245B1
ITM00140.50A1

INPUT [Same Ref but Different ItemValue] :

ItemNoItemValueRef
ITM00181A1
ITM00245B1
ITM00130A1

Expected OUTPUT [No Change to Value]:

ItemNoItemValueRef
ITM00181A1
ITM00245B1
ITM00130A1

Expected INPUT [ Different Ref Same ItemValue] :

ItemNoItemValueRef
ITM00181A1
ITM00245B1
ITM00181A2

Expected OUTPUT [ No Changes to ItemValue]:

ItemNoItemValueRef
ITM00181A1
ITM00245B1
ITM00181A2

Rows are duplicating due to other column s.

SELECT ItemNo, AVG(ItemValue) OVER (PARTITION BY ItemNo) / COUNT(*) OVER(PARTITION BY ItemNo) AS ItemValue 
FROM ItemDetails ;

seems not working .

Can anyone please help ?

b1zrtrql

b1zrtrql1#

This gives the outputs you indicated in your post; note that if your ItemValue column is a float, this will behave unpredictably and should be cast to a decimal or numeric type first.

/*
CREATE TABLE #ItemDetails (
  ItemNo NVARCHAR(255),
  ItemValue DECIMAL(10,2)
)
INSERT INTO #ItemDetails VALUES ('ITM001', 81)
INSERT INTO #ItemDetails VALUES ('ITM002', 45)
INSERT INTO #ItemDetails VALUES ('ITM001', 81)
INSERT INTO #ItemDetails VALUES ('ITM003', 81)
INSERT INTO #ItemDetails VALUES ('ITM004', 45)
INSERT INTO #ItemDetails VALUES ('ITM003', 30)
*/
WITH DuplicateCounts AS (
  SELECT
    ItemNo,
    ItemValue,
    COUNT(*) AS DuplicateCount
  FROM
    #ItemDetails
  GROUP BY
    ItemNo,
    ItemValue
)
SELECT 
  I.ItemNo,
  I.ItemValue/D.DuplicateCount AS ItemValue
FROM 
  #ItemDetails I
INNER JOIN
  DuplicateCounts D
ON
  I.ItemNo = D.ItemNo
  AND I.ItemValue = D.ItemValue

相关问题