SQL 服务器:查询以获取 Table1 的 Col1 中的值的总和,以满足 Table2 的 Col2 中的条件

SQL Server : query to get sum of values in Col1 of Table1 for a condition in Col2 of Table 2

我有两张桌子。 Table1 有 Col1 和 Col2,Table2 有 Col1 和 Col3。 所以 col1 名称在两个表中都很常见。

我需要一个查询,该查询应该对常见 ROW ID(Table1-col1 值)的匹配字符串求和

附上这张截图:

我会试试这个(针对空值和空格更新):

SELECT 'Success', SUM(t2.Col2) FROM Table1 t1 JOIN Table2 t2 ON t1.Col1 = t2.Col1 WHERE t1.Col2 = 'Success' UNION ALL
SELECT 'Failure', SUM(t2.Col2) FROM Table1 t1 JOIN Table2 t2 ON t1.Col1 = t2.Col1 WHERE t1.Col2 = 'Failure' UNION ALL
SELECT 'NULL', SUM(t2.Col2) FROM Table1 t1 JOIN Table2 t2 ON t1.Col1 = t2.Col1 WHERE t1.Col2 IS NULLUNION ALL
SELECT 'EMPTY SPACE', SUM(t2.Col2) FROM Table1 t1 JOIN Table2 t2 ON t1.Col1 = t2.Col1 WHERE t1.Col2 = ' '

会给你两行你想要的结果。

  • UNION ALL 简单地连接两行或更多行(具有相同的列); ALL 告诉忽略重复项(这不是问题,实际上可以提高性能)
  • SUM当然是对一列中的所有单元格求和
  • JOIN will "merge" your tables

A JOIN clause is used to combine rows from two or more tables, based on a related column between them.