简体   繁体   English

如何从一个表中选择两个SUM,但只能从一个表中选择一个SUM。 数据

[英]How to select two SUMs from one table but one SUM must be made from only max. data

I have this table 我有这张桌子

Room       Papers    Pens
1           30        30
3           10        10
4           15        15
4           35        25
3           25        5
2           15        45
2           5         15
4           7         8
4           11        9
4           12        11
1           8         8

I need to get SUM(Papers) for Rooms 2,4 which I know how to get (it will be together 100) but then I need also get in this query SUM(Pens) also for Rooms 2,4 BUT only for highest value for each Room. 我需要获得房间2,4的SUM(论文),我知道如何获得(它将在一起100)但是我还需要获得此查询SUM(笔)也适用于房间2,4但仅为了最高价值每个房间。 It will be for Room 2 value 45 and for Room 4 value 25 in this table and SUM must be 70. 它将用于房间2值45和此表中房间4值25,并且SUM必须为70。

I have used this code but ofcourse it is not working correct for Pens value... 我已经使用过这段代码,但是当然它对Pens值不正确...

SELECT SUM(Papers) AS Papers, SUM(DISTINCT Pens) AS Pens FROM MyTable
WHERE (Room = '2' OR Room = '4')

THX for help THX寻求帮助

You can do it with conditional aggregation: 您可以使用条件聚合来完成:

SELECT 
  SUM(Papers) AS Papers, 
  SUM(
    CASE 
      WHEN EXISTS (
        SELECT 1 FROM MyTable 
        WHERE Room = m.Room AND Pens > m.Pens 
      ) THEN 0 
      ELSE Pens 
    END 
  ) AS Pens
  FROM MyTable m
WHERE (Room = '2' OR Room = '4')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从一个表中选择数据,按另一表中的数据总和排列 - Select data from one table, arrange by a sum of data from another 如何从两个表中进行选择,并且仅显示一个表中的一项,而第二个表中的多项呢? - How to select from two tables and display only one item from 1 table and many from the second table? 如何从一张表中选择两行? - How to select two rows from one table? PHP / SQL:仅使用一个查询,如果两个表中都有数据,则从两个表中选择行;否则,仅从一个表中进行SELECT - PHP/SQL: Using only one query, SELECT rows from two tables if data is in both tables, or just SELECT from one table if not 如何从两个表中选择数据,而两个表只为第一表的一行选择了第二表的第一行 - How to SELECT data from two tables which only first row of second table is selected for one row of first table 如何在MySQL中选择两个表,但仅从第二个表中选择一列? - How can I select two tables in MySQL but only select one column from the 2nd table? 如何从B表中仅选择一行? - How to select only one row from B table? 如何从一个表中选择与另一个表的(和)差? - How to select from one table where difference with (sum) from another table? 如何从一个表而不是两个表中将此MySQL查询更改为SELECT? - How to change this MySQL query to SELECT from one table instead of two? 如何从两个表连接中 select 一个值? - How to select one value from a two table join?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM