简体   繁体   中英

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. 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. How should the query be structured so I can use Alpha through Theta as parameters but still aggregate 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)

Why don't you just select all the greeks, Xi and Omicron in one select statement and calculate the sum in the host language? That's one potentially costly query instead of two.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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