我正在尝试group by
。但是,这个唯一的id字段阻止我这样做。
您能帮我解决一下这个问题。
感谢。
方案1
select box.name, box.description, box.id
from box
group by box.name, box.description, box.id
order by box.id
更新: 我已经解决了第一个场景 http://sqlfiddle.com/#!6/111e7/16/0
方案2
select box.name, box.description, box.id, sum(box.amount) as amount
from box
group by box.name, box.description, box.id
order by box.id
更新: 我已经解决了第二种情况 http://sqlfiddle.com/#!6/449b7/2
答案 0 :(得分:1)
删除重复
;WITH xx AS
(
select
[rn] = ROW_NUMBER() OVER (PARTITION BY ID, ORDER BY Id),
name, description, id
from box
)
SELECT
*
FROM xx
WHERE
[rn] = 1
或者
SELECT TOP 1 WITH TIES
*
FROM xx
ORDER BY
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Id)
答案 1 :(得分:0)
一种方法是保持MAX或MIN框ID并使用它来排序。这将删除重复项,仍然为您提供订购价值。例如(使用MAX)
select box.name, box.description, MAX(box.id) box_id, sum(box.amount) as amount
from box
group by box.name, box.description, box.id
order by MAX(box.id)