简体   繁体   English

与聚合组件的SQL联合

[英]sql union with an aggregation component

I have a query that I use for charting in reporting services that looks something like: 我有一个查询,用于在报表服务中进行图表绘制,如下所示:

(SELECT Alpha, Beta, Gamma, Delta, Epsilon, Zeta, Eta, Theta, Iota, Kappa, Lambda, Mu,Nu, Xi from tbl 
WHERE    
Alpha in (@Alphas) and 
Beta in (@Betas) and
Gamma in (@Gammas)  and
Delta in (@Deltas) and
Epsilon in (@Epsilons) and
Zeta in (@Zetas) and
Eta in (@Etas) and
Theta in (@Thetas) )
UNION 
(SELECT Alpha, Beta, Gamma, Delta, Epsilon, Zeta, Eta, Theta, Iota, Kappa, Lambda, Mu,Nu, Omicron from tbl 
WHERE    
Alpha in (@Alphas) and 
Beta in (@Betas) and
Gamma in (@Gammas)  and
Delta in (@Deltas) and
Epsilon in (@Epsilons) and
Zeta in (@Zetas) and
Eta in (@Etas) and
Theta in (@Thetas))

Alpha through Theta are to be used to in a couple of calculated fields which concatenate them (say Alpha, Beta, Gamma) into a string in one field. Alpha至Theta将用于两个计算字段中,这些字段将它们(例如Alpha,Beta,Gamma)连接到一个字段中的字符串中。 The select statement for Omicron will generate the same number of rows as Xi but what I really want is to aggregate Omicron, so if the Select query with Xi produces 9 legend item, the aggregate select for Omicron should only produce one legend item because the values Alpha through Theta are not important for Omicron. Omicron的select语句将生成与Xi相同的行数,但我真正想要的是聚合Omicron,因此,如果使用Xi的Select查询生成9个图例项,则Omicron的聚合select应该只生成一个图例项,因为值Alpha至Theta对Omicron而言并不重要。 How should the query be structured so I can use Alpha through Theta as parameters but still aggregate Omicron? 如何构造查询,以便我可以通过Theta使用Alpha作为参数,但仍可以聚合Omicron?

I'm not sure what you really want, but if I understood correctly, you can try something like: 我不确定您真正想要的是什么,但是如果我理解正确,则可以尝试以下操作:

(SELECT a,b,c,d FROM k
WHERE a in (@a) and b in (@b) and c in (@c))
UNION
(SELECT NULL,NULL,NULL,sum(e) FROM k
WHERE a in (@a) and b in (@b) and c in (@c) GROUP BY e)

NULLs just for being able to perform the union (maintaining the amount of columns, you might have to do column aliasing) 仅仅为了能够执行并集就为NULL(保持列的数量,您可能必须做列别名)

Why don't you just select all the greeks, Xi and Omicron in one select statement and calculate the sum in the host language? 您为什么不只在一个select语句中选择所有希腊语,Xi和Omicron并以宿主语言计算总和? That's one potentially costly query instead of two. 那是一个潜在的昂贵查询,而不是两个。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM