当子查询中的SUM权重时,SQL DISTINCT id

时间:2015-02-16 11:14:02

标签: sql sql-server distinct

我在语句中有两种类型的子查询。 首先是一些样本数据。

表格

CAT   ID    Weight   GROUP
1      1     200     A  
1      2     300     B  
1      3     250     B 
1      1     200     A  
1      4     200     A

一个子查询是按预期工作的不同ID的计数。

( SELECT COUNT (distinct t1.ID) 
FROM table t1
WHERE t1.group = 'A'
GROUP BY t1.cat)
AS [count],

另一个子查询是权重的总和

( SELECT SUM(t1.weight) 
FROM table t1
WHERE t1.group = 'A'
GROUP BY t1.cat)
AS [weight],

这并没有给我我需要的东西,因为当我想要它总计400时它将总计600,因为我只想使用唯一ID作为第一个查询。

然而,通过添加明显的......

( SELECT SUM(DISTINCT t1.weight) 
FROM table t1
WHERE t1.group = 'A'
GROUP BY t1.cat)
AS [weight],

这只返回200,因为它使用不同的重量,我想要的是它在这里使用不同的ID,但我怎么能这样做而仍然只选择重量?

类似的东西(从逻辑上讲,因为这不起作用)

( SELECT SUM(t1.weight) 
FROM table t1
WHERE t1.group = 'A'
AND t1.ID IS DISTINCT
GROUP BY t1.cat)
AS [weight],

2 个答案:

答案 0 :(得分:3)

 SELECT cat,SUM(weight) AS [weight] FROM 
(SELECT *,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID) as rn
 FROM table ) as tbl
WHERE [group] = 'A' AND rn=1
GROUP BY cat

答案 1 :(得分:1)

我可能会遗漏一些内容,因为我已经查看了您的示例数据以及我认为您想要的输出,但您不能只做一个简单的GROUP BYSUM:< / p>

CREATE TABLE SampleData
    ([CAT] int, [ID] int, [Weight] int, [GROUP] varchar(1))
;

INSERT INTO SampleData
    ([CAT], [ID], [Weight], [GROUP])
VALUES
    (1, 1, 200, 'A'),
    (1, 2, 300, 'B'),
    (1, 3, 250, 'B'),
    (1, 1, 200, 'A'),
    (1, 4, 200, 'A')
;

SELECT ID, COUNT(ID) AS [Counter], SUM(Weight) AS SumWeight
FROM SampleData
WHERE [GROUP] = 'A'
GROUP BY ID

生产:

ID  Counter SumWeight
1   2       400
4   1       200