我正在努力完成以下任务:
SELECT
*,
CASE WHEN 1 THEN SUM(b.myField) ELSE AVG(b.myField) END OVER (PARTITION BY ID)
FROM tbl a
LEFT JOIN tbl2 b ON a.ID = b.aID
这是否可以使用SQL Server中的窗口函数?
我可以在没有case语句的情况下完成以下操作:
SELECT
*,
SUM(b.myField) OVER (PARTITION BY ID)
FROM tbl a
LEFT JOIN tbl2 b ON a.ID = b.aID
答案 0 :(得分:1)
你可以试试这个:
SELECT
*,
CASE WHEN (SUM(b.myField)
OVER (PARTITION BY ID))=1 THEN SUM(b.myField)
ELSE AVG(b.myField) END
FROM tbl a
LEFT JOIN tbl2 b ON a.ID = b.aID
答案 1 :(得分:0)
你可以这样做
SELECT *, CASE
[something]
WHEN 1 THEN SUM(myfield) OVER (PARTITION BY ID)
ELSE AVG(myfield) OVER (PARTITION BY ID) END
FROM yourtable
我不确定你应该这样做,不过
答案 2 :(得分:0)
我认为您需要将其包装在cte中以获得独特的结果:
CREATE TABLE #temp (ID INT, myField DECIMAL(6,2))
INSERT INTO #temp
( ID, myField )
VALUES ( 1,1 ),(1,2),(1,3),(1,4),(2,2),(2,10),(3,4),(4,4),(4,2)
;WITH cte AS (SELECT ID ,
CASE WHEN ID = 1 THEN AVG(MyField) OVER ( PARTITION BY ID )
ELSE SUM(MyField) OVER ( PARTITION BY ID )
END AS SumOrAvg
FROM #temp)
SELECT DISTINCT ID, SumOrAvg
FROM cte
DROP TABLE #temp