【问题标题】:Is there a way to have a distinct clause and SUM clause at the same time?有没有办法同时有一个不同的子句和 SUM 子句?
【发布时间】:2020-01-27 17:12:46
【问题描述】:

我的数据库中有这张表,它存储了工具应用程序发出的请求的数据。

select * from details

IdDetail | Folio | IdTool | Cost |
1        |53     |917     |137   |
2        |53     |918     |145   |
3        |53     |919     |15    |
4        |54     |917     |137   |
5        |54     |917     |137   |
6        |54     |916     |56    |

它存储请求信息(Folio)、工具信息(IdHerramienta 和 Gasto[Cost])。我的目标是获得一个语句来获取详细信息的数据,仅显示每行不同的 IdHerramienta(IdTool),其中有多少具有相同的 Folio,以及 IdTool 重复时的成本总和(如果工具在同一个 Folio 中出现多次,每次重复都会增加它的成本)

到目前为止,我只能显示一个工具重复了多少次,但我也想知道成本,关于如何获得它有什么想法吗?

select distinct IdTool, count(IdTool) as Quantity 
from details where Folio = 54 group by IdTool

| IdTool | Quantity |
|917     |2         |
|916     |1         |

我想得到的结果

Folio | IdTool | Quantity | Cost  |
54    |917     |2         |274    |
54    |916     |1         |56     |

【问题讨论】:

  • 代码和数据的图像确实没有帮助。请花时间以text的格式提供两者。
  • 请显示想要的结果。
  • 获得累积结果的好方法是使用With。
  • 以文本格式编辑数据并按照建议添加所需结果

标签: sql sql-server tsql count distinct


【解决方案1】:

你似乎在寻找聚合:

select folio, id_tool, count(*) quantity, sum(cost) cost
from mytable
where folio = 56
group by folio, id_tool

【讨论】:

    【解决方案2】:

    我认为以下内容可以满足您的要求:

    select idherramienta, count(*), avg(gasto)
    from t
    where folio = 56
    group by idherramienta
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-04
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      相关资源
      最近更新 更多