更新:请查看第二个查询,它对此示例更具代表性
我想创建一个为每列使用不同子查询的查询。 子查询将基于外部查询获得的列表。
例如: 考虑tableA是一个包含30列和500万条记录的表
SELECT a, b, c,
(SELECT COUNT(a) FROM values WHERE (r = 12 AND u = 'TO') OR (r = 16 AND u IN ('TB', 'TU')) as First,
(SELECT COUNT(a) FROM values WHERE (r = 16 AND u = 'TE') OR (r = 76 AND u IN ('TE', 'TG')) as Second,
(SELECT COUNT(a) FROM values WHERE (r = 564 AND u = 'HG') OR (r = 788 AND u IN ('VD', 'BF')) as Third,
(SELECT COUNT(a) FROM values WHERE (r = 383 AND u = 'RT') OR (r = 35 AND u IN ('GR', 'EZ')) as Fourth
FROM tableA values
我知道这个查询不会执行,因为我无法调用子查询中的值,但是有一个很好的解决方案可以让这个查询快速运行吗?
在某些子查询中,我还需要加入另一个表,是否仍然可以使用值,还是我必须再次在tableA上执行子查询?
以下查询对此示例更具代表性:
SELECT col1, col2,
(SELECT COUNT(col3) FROM tableA ta
INNER JOIN tableB b ON tl.TaskId = b.col6
INNER JOIN tableC c ON b.Id = c.TaskId
WHERE c.ResultCode = 1 AND ta.col4 = a.col4 AND ta.col5 = a.col5) as Executed,
(SELECT COUNT(col3) FROM tableA ta
INNER JOIN tableB b ON tl.TaskId = b.col6
INNER JOIN tableC c ON b.Id = c.TaskId
WHERE c.ResultCode = 9 AND ta.col4 = a.col4 AND ta.col5 = a.col5) as NotExecuted
FROM tableA a
GROUP BY col1, col2, col4, col5
答案 0 :(得分:0)
SELECT a, b, c,
SUM(CASE WHEN a IS NOT NULL AND b=12 THEN 1 ELSE 0 END) as First,
SUM(CASE WHEN a IS NOT NULL AND b=16 THEN 1 ELSE 0 END) as Second,
SUM(CASE WHEN a IS NOT NULL AND b=82 THEN 1 ELSE 0 END) as Third,
SUM(CASE WHEN a IS NOT NULL AND b=167 THEN 1 ELSE 0 END) as Fourth
FROM tableA
GROUP BY a, b, c