查找sql​​ 2005中所有记录的列值的总和

发布于 2024-08-20 06:59:43 字数 599 浏览 2 评论 0原文

我想查找权重列中值的总和。我想要在名称列之一中用公共值标识的所有记录的总和。此外,我只想考虑那些在类型列中具有特定值的记录。

名称 重量 类型
1 $ 12.00 A
2 $ 7.00 B
2 $ 7.00 A
1 $ 1.00 C
2 $ 7.00 B
1 $ 1.00 C
2 $ 7.00 B
1 $ 7.00 B
2 $ 7.00 C
2 $ 7.00 B

我想要类型 A 和 B 的名称 2 的总权重。可以为此编写子查询吗?或者只能进行循环。 Tnx。

I want to find the SUM of values in a column weight. I want this sum for all records that are identified with a common value in one of the columns name. Further, I want to consider only those records that have a certain value in the column type.

name weight type
1 $ 12.00 A
2 $ 7.00 B
2 $ 7.00 A
1 $ 1.00 C
2 $ 7.00 B
1 $ 1.00 C
2 $ 7.00 B
1 $ 7.00 B
2 $ 7.00 C
2 $ 7.00 B

I want the total weight for name 2, for the types A and B. Can a subquery be written for this or only looping can be done. Tnx.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

转身以后 2024-08-27 06:59:43
SELECT
    Name,
    Type,
    SUM(Weight)
FROM
    MyTable
GROUP BY
    Name,
    Type
HAVING
    Name = @name
AND
    Type = @type

或者具体针对您的请求

SELECT
    Name,
    Type,
    SUM(Weight)
FROM
    MyTable
GROUP BY
    Name,
    Type
HAVING
    Name = '2'
AND
    Type IN('A', 'B')

但是,如果您的过滤器纯粹是单个值,那么您可以使用 WHERE 子句进行求和。

SELECT
    SUM(Weight)
FROM
    MyTable
WHERE
    Name = '2'
AND
    Type IN('A', 'B')
SELECT
    Name,
    Type,
    SUM(Weight)
FROM
    MyTable
GROUP BY
    Name,
    Type
HAVING
    Name = @name
AND
    Type = @type

Or to be specific for your request

SELECT
    Name,
    Type,
    SUM(Weight)
FROM
    MyTable
GROUP BY
    Name,
    Type
HAVING
    Name = '2'
AND
    Type IN('A', 'B')

However, if it is purely a single value you are after for your filter then you can just SUM with a WHERE clause.

SELECT
    SUM(Weight)
FROM
    MyTable
WHERE
    Name = '2'
AND
    Type IN('A', 'B')
栩栩如生 2024-08-27 06:59:43

这实际上取决于人们对OP问题的解释,这对我来说有点模糊。但尝试一下:

SELECT
    SUM(Weight)
    FROM MyTable
    WHERE Name=2 AND Type IN ('A','B','C')

this really depends on ones interpretation of the OPs question, which is a little vague to me. But give this a try:

SELECT
    SUM(Weight)
    FROM MyTable
    WHERE Name=2 AND Type IN ('A','B','C')
捎一片雪花 2024-08-27 06:59:43

这将显示每个名称的权重总和,其中类型为 A 或 B:

select name, sum(weight) as WeightSum
from MyTable t
where type in ('A', 'B')
group by name

This will show you the sum of weights for each name, where the type is A or B:

select name, sum(weight) as WeightSum
from MyTable t
where type in ('A', 'B')
group by name
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文