我有一个包含3列的表(MyTable);数量,线,金额。
如果Number在3个以上的记录中相同,我想返回按Number分组的记录。否则我想要按数字和行分组的所有其他记录。
这是我到目前为止所得到的。它给出了一个错误,因为Line需要在聚合函数中
select * (
select Number, (case when count(Line) > 3 then -1 else Line end) as Line2, sum(Amount)
from MyTable
group by Number, Line2
) as x
order by x.Number
MyTable看起来像这样:
Number Line Amount
------------------------
1 1 100
1 1 100
1 2 200
1 2 200
2 1 150
2 1 150
3 1 300
3 2 350
我希望结果看起来像这样:
Number Line2 Amount
------------------------
1 -1 600 <- More than 3 lines
2 1 300 <- Grouped by Line
3 1 300
3 2 350
答案 0 :(得分:4)
试试这个:
SELECT Number, -1 AS Line, SUM(Amount) AS Amount
FROM mytable
GROUP BY Number
HAVING COUNT(*) > 3
UNION
SELECT Number, Line, SUM(Amount) AS Amount
FROM mytable
WHERE Number NOT IN (SELECT Number
FROM mytable
GROUP BY Number
HAVING COUNT(*) > 3)
GROUP BY Number, Line
答案 1 :(得分:3)
您可以像这样使用CTE:
DECLARE @t table
(Number int,Line int,Amount int)
INSERT @t VALUES
(1,1,100),(1,1,100),(1,2,200),
(1,2,200),(2,1,150),(2,1,150),
(3,1,300),(3,2,350)
;WITH CTE as
(
SELECT
Number, Line, Amount,
count(*) over (partition by number) cnt
FROM @t
)
SELECT
Number,
CASE WHEN cnt < 3 THEN Line ELSE -1 END Line2,
SUM(Amount) Amount
FROM CTE
GROUP BY number, CASE WHEN cnt < 3 THEN Line ELSE -1 END
结果:
Number Line Amount
1 -1 600
2 1 300
3 1 300
3 2 350