简体   繁体   English

如何返回两行联合和每行的计数?

[英]How do I return two lines of unions and a count for each row?

I'm trying to take 10 columns and put into one column, take 10 more different columns into a separate column and get a count for each unique couple in a third column.我正在尝试将 10 列放入一列,再将 10 个不同的列放入一个单独的列中,并为第三列中的每一对独特的夫妇计数。

So far I've got到目前为止我有

UNION
(SELECT a_3 as x, a_4 as y FROM result)
....
UNION
(SELECT a_19 as x, a_20 as y FROM result)

This gives me a table as follows这给了我一张如下表

| x | y |
---------
| a | 1 |
| a | 2 |
| b | 1 |
| b | 3 |
etc...

I want this, however I also want a third column counting how many times each row occurs, like below我想要这个,但是我还想要第三列计算每行出现的次数,如下所示

| x | y |count|
---------------
| a | 1 | 10 |
| a | 2 | 3  |
| b | 1 | 6  |
| b | 3 | 2  |
etc...

I can also do:我也可以这样做:

select count(*) from (insert above union SQL)

but then I just get a total number for the table.但后来我只得到了表格的总数。

Thanks!谢谢!

SELECT X,Y,COUNT(1) AS[COUNT] FROM
(
 SELECT a_3 as x, a_4 as y FROM result
 ....
 UNION
 SELECT a_19 as x, a_20 as y FROM result
) x
GROUP BY X,Y

Looks like your original table design is not normalized at all.看起来您的原始表格设计根本没有标准化。

Instead of multiple union query, you can use CROSS APPLY with Table Value Constructor to simplify the query您可以使用带有Table Value ConstructorCROSS APPLY来简化查询,而不是多个联合查询

select  x, y, count(*) as [count]
from    [result] t
        cross apply
        (
            values (a_1, a_2), (a_3, a_4), (a_5, a_6), 
                   . . . 
                   (a_19, a_20)
        ) v (x, y)
group by x, y

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

相关问题 如何计算联接表的每一行中值的出现次数? - How do I count the occurences of the values in each row of a joined table? 我如何将两个查询与其中的每个计数和条件相加 - How do i sum two query with each count and criteria in it 如何将两个查询的结果返回到彼此之下 - How do I return the result of two queries below each other 对于具有周数值的每一行,如何计算前几周的行数? - For each row with a week number value, how do I count the number of rows from the previous weeks? SQL:如何获取表中每个不同行的筛选计数? - SQL: How do I get a filtered count for each distinct row in a table? 如何应用COUNT()列(针对每一行计算)而不在O(n ^ 2)中运行 - How do I apply a COUNT() column (calculated for each row) without making my run in O(n^2) 如何获取LIKE和COUNT以返回行数少于该行中未包含的值的行数? - How do I get LIKE and COUNT to return the number of rows less than a value not in the row? 如何在返回集中获取每行的空值列数? - How do I get the count of null value columns per row in a return set? 如何在 codeigniter 上使用 select as 进行多个联合? - How do I do multiple unions with select as on codeigniter? 返回每行SQL中记录的数量 - Return count of records in each row SQL
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM