SQL Server Sum Distinct Group by

时间:2018-06-05 05:16:02

标签: sql sql-server

例如,这个表格,我需要将其与id和日期分组,并使用不同的

id      amt          date
1       100          2018/06/01
1       120          2018/06/02
1       100          2018/06/03
1       100          2018/06/03
1       100          2018/06/03
2       100          2018/06/01
2       100          2018/06/01
2       100          2018/06/01
2       130          2018/06/02
2       130          2018/06/02
2       130          2018/06/02
2       130          2018/06/02
2       100          2018/06/03

首先我试过

SELECT SUM(DISTINCT amt) GROUP BY id

但结果是错误的,例如在id 1上删除了重复内容,而不是320,它只会导致220,因为它会删除重复的amt 100。

所以我试过

SELECT SUM(DISTINCT amt) GROUP BY id, date

但我无法总结。

编辑:对不起,我忘了说结果应该是

id      amt
1       320
2       330

5 个答案:

答案 0 :(得分:4)

具有长版本,但查询易于理解。使用CTE的以下查询可以帮助您

with records as
(select distinct id, date, amt from table_name)
select sum (amt), id
from records
group by 
id;

答案 1 :(得分:1)

尝试以下。

SELECT id,SUM(DISTINCT amt) as amt,date #tmp from [yourTableName] GROUP BY id, date

select id,amt from #tmp

答案 2 :(得分:1)

试试这个:

select id, SUM(amt) from (
    select id, SUM(distinct amt) amt, [date] from @tbl
    group by id, [date]
) a group by id

首先,您需要对按amtid分组的不同date进行分组。接下来,您必须按id对结果进行分组,汇总部分求和的amt列(在第一步中,我们只汇总了特定日期的不同值)。

答案 3 :(得分:1)

试试这个......

SELECT id, 
       Sum(amt) AS amt 
FROM   (SELECT DISTINCT * 
        FROM   mytable) tbl 
GROUP  BY id 

输出

+----+-----+
| id | amt |
+----+-----+
|  1 | 320 |
|  2 | 330 |
+----+-----+

SQL FIDDLE:http://sqlfiddle.com/#!18/2d356/14/0

答案 4 :(得分:0)

使用CTE和Row_number的以下查询可以帮助您

with cte
as
(      
select 1 id, 100 amt,cast('2018/06/01' as date) date
union all
select 1 id, 120 amt,cast('2018/06/02' as date) date
union all
select 1 id, 100 amt,cast('2018/06/03' as date) date
union all
select 1 id, 100 amt,cast('2018/06/03' as date) date
union all
select 1 id, 100 amt,cast('2018/06/03' as date) date
union all
select 2 id, 100 amt,cast('2018/06/01' as date) date
union all
select 2 id, 100 amt,cast('2018/06/01' as date) date
union all
select 2 id, 100 amt,cast('2018/06/01' as date) date
union all
select 2 id, 130 amt,cast('2018/06/02' as date) date
union all
select 2 id, 130 amt,cast('2018/06/02' as date) date
union all
select 2 id, 130 amt,cast('2018/06/02' as date) date
union all
select 2 id, 130 amt,cast('2018/06/02' as date) date
union all
select 2 id, 100 amt,cast('2018/06/03' as date) date
)
select id,sum(amt) as sum1 from 
(
select *,ROW_NUMBER() over(partition by id,date order by id,date) s1 from cte
) b
where s1=1
group by id