[英]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 Constructor
的CROSS 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.