SQL DISTINCT id when SU​​M weight in sub query

SQL DISTINCT id when SUM weight in sub query

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

Table

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],

这只有 returns 200,因为它使用不同的权重,我想要的是它在其中使用不同的 ID,但是我如何在仍然只选择权重的情况下做到这一点?

类似的东西(从逻辑上讲这是行不通的)

( SELECT SUM(t1.weight) 
FROM table t1
WHERE t1.group = 'A'
AND t1.ID IS DISTINCT
GROUP BY t1.cat)
AS [weight],
 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

我可能遗漏了一些东西,因为我查看了您的样本数据,我认为这是您想要的输出,但您能不能只做一个简单的 GROUP BYSUM:

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