我有一种情况,我希望消除在页面上执行的查询数量。假设我有一个结果集,称为filtered_table:
SELECT
col_a
,col_b
,col_c
FROM
table
where
col_a = 1
然后我得到了一组所有可能的结果,分别是未过滤查询,distinct_col_a,distinct_col_b,distinct_col_c。
SELECT
distinct col_a
FROM
table
SELECT
distinct col_b
FROM
table
SELECT
distinct col_c
FROM
table
最后,对于每个值distinct_col_a,distinct_col_b,distinct_col_c可以包含,我执行查询的查询中filtered_table得到的计数。
(for each value in distinct_col_a)
SELECT
count(col_a)
FROM
filtered_table
笨重且资源丰富。我觉得应该有某种方法来汇总,而不是每个都汇总,一次就获得这些数字,但是我无法解决这个问题。
例如:
table
col_a | col_b | col_c
1 | a | x
2 | b | y
3 | c | z
3 | c | x
1 | d | x
filtered_table,使用where col_a = 1
col_a | col_b | col_c
1 | a | x
1 | d | x
我正在寻找的结果:
col_name| col_value| number results
col_a | 1 | 2
col_a | 2 | 0
col_a | 3 | 0
col_b | a | 1
col_b | b | 0
col_b | c | 0
col_b | d | 1
col_c | x | 2
col_c | y | 0
col_c | z | 0
答案 0 :(得分:1)
我们可以使用unpivot
和单独的聚合的时髦组合来在一个相当紧凑的查询中创建这些结果:
declare @t table (col_a char(1), col_b char(1), col_c char(1))
insert into @t(col_a,col_b,col_c) values
('1','a','x'),
('2','b','y'),
('3','c','z'),
('3','c','x'),
('1','d','x')
select
col_name, col_value, SUM(Cnt) as results_count
from
(select *,CASE WHEN col_a = 1 THEN 1 ELSE 0 END as Cnt from @t) t
unpivot
(col_value for col_name in (col_a, col_b, col_c)) p
group by col_name,col_value
结果:
col_name col_value results_count
--------- --------- -------------
col_a 1 2
col_a 2 0
col_a 3 0
col_b a 1
col_b b 0
col_b c 0
col_b d 1
col_c x 2
col_c y 0
col_c z 0
(注意-这些结果的输出顺序与您期望的输出顺序相同。但是目前没有ORDER BY
子句,因此无法保证)
不是在WHERE
表达式中应用“ CASE
子句”作为检查。如果您看不到它是如何立即运行的,建议您运行
select
*
from
(select *,CASE WHEN col_a = 1 THEN 1 ELSE 0 END as Cnt from @t) t
unpivot
(col_value for col_name in (col_a, col_b, col_c)) p
首先查看unpivot
产生的效果。