【问题标题】:SQL query of sums of joined table values连接表值总和的 SQL 查询
【发布时间】:2018-05-09 10:05:33
【问题描述】:

尝试在一个查询和一行中获取不同行的计数

表 1..

ID name 
1   a
2   b
3   c

表 2

ID Parent status
1   1     0
2   1     1
3   1     0
4   1     0
5   1     2
6   2     0

期望的结果(不同子元素的计数)

ID   name 0a             1s               2s
1    a    3(count of 0s) 1 (counts of 1s) 2 (count of 2s)

我们可以在一个查询中得到这个吗..

我尝试过的结果是 3 行中的值

Select t1.id, t1.name, count(status) from TABLE_1 t1 Left JOIN TABLE_2 t2
ON t1.id = t2.parent
group by status



ID   name status 
1    a    3
1    a    1
1    a    1
2    b    1

【问题讨论】:

  • 你用什么? MySql 或 SqlServer - sql 方言的实现方式不同。看起来您可以在连接的表上使用 PIVOT:看看这里:stackoverflow.com/questions/13372276/…
  • 一旦你弄清楚你使用的是哪个RDBMS,实际上考虑处理应用程序代码中的数据显示问题。
  • 它现在是 Mysql.. 觉得没关系
  • 我同意...我想先确认...否则将处理它们在应用程序中的分组
  • 我觉得2s的值应该是1吧?

标签: mysql sql-server join


【解决方案1】:
Select t1.id, t1.name, 
       (select count(*) from t2 where t2.parent = t1.id and status=0) as 0s,
       (select count(*) from t2 where t2.parent = t1.id and status=1) as 1s,
       (select count(*) from t2 where t2.parent = t1.id and status=2) as 2s
       from t1 inner join t2
ON t1.id = t2.parent
group by t1.id;

【讨论】:

  • 我将提供另一种方法,但如果您没有大型数据集,它会起作用。
  • 我对其进行了测试,它工作正常……只需花费 10 秒记录的正常选择查询的两倍时间……它可能会随着大量数据而变化。 ...但感谢您的指导
【解决方案2】:

您可以为此使用条件聚合

Select t1.id, t1.name, 
       coalesce(sum(status=0), 0) AS '0s', 
       coalesce(sum(status=1), 0) AS '1s',
       coalesce(sum(status=2), 0) AS '2s'
from TABLE_1 t1 
Left JOIN TABLE_2 t2 ON t1.id = t2.parent
group by t1.id, t1.name

Demo here

【讨论】:

  • 一种更简单有效的方法。
【解决方案3】:

您可以左连接并将 Count 与 Case 语句一起使用。例如:

SELECT T1.ID
      ,T1.name
      ,COUNT(CASE WHEN T2.status = 0 THEN T2.ID END) [0a]
      ,COUNT(CASE WHEN T2.status = 1 THEN T2.ID END) [1s]
      ,COUNT(CASE WHEN T2.status = 2 THEN T2.ID END) [2s]
  FROM TABLE_1 T1 LEFT JOIN TABLE_2 T2 ON T1.ID = T2.Parent
GROUP BY T1.ID, T1.name  

将产生输出:

ID  name    0s  1s  2s
1   a       3   1   1
2   b       1   0   0
3   c       0   0   0

这是 sqlfiddle 中的完整代码:http://sqlfiddle.com/#!6/ab92d/10/0

【讨论】:

  • 所有三个解决方案都有效,但这是所有解决方案中花费时间最少的查询,因此将其标记为答案。
猜你喜欢
  • 2023-03-14
  • 1970-01-01
  • 2020-07-15
  • 2020-07-15
  • 1970-01-01
  • 2017-11-21
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
相关资源
最近更新 更多