简体   繁体   English

跨列的SQL计数

[英]SQL Count across columns

I know that this table structure is horrible and that I should look into database normalization, but this is what I have to work with at the moment. 我知道这个表结构太可怕了,我应该研究数据库规范化,但这是我现在必须要处理的。

I need to find the most common number across the columns where one of them has a specific id (in my example 3 ). 我需要其中一个具有特定ID 的列中找到最通用的数字(在我的示例3 )。 Both columns will never have the same value. 两列永远不会具有相同的值。

Query 询问

SELECT Col1, Col2 FROM scores WHERE Col1 = 3 OR Col2 = 3

Result 结果

+------+------+
| Col1 | Col2 |
+------+------+
|    1 |    3 |
|    3 |    1 |
|    2 |    3 |
|    6 |    3 |
|    3 |    7 |
|    3 |    9 |
|    2 |    3 |
|    5 |    3 |
+------+------+

I'm hoping to get a result like this (I don't need count for 3 since it's the ID, but it can be included) 我希望得到这样的结果(因为ID是ID,所以我不需要计数3,但是可以包含在内)

+-------+-------+
| Value | Count |
+-------+-------+
|     1 |     2 |
|     2 |     2 |
|     5 |     1 |
|     6 |     1 |
|     7 |     1 |
|     9 |     1 |
+-------+-------+

I've tried a few things such as UNION and nested SELECT but that doesn't seem to solve this thing. 我已经尝试了一些事情,例如UNION和嵌套SELECT但这似乎并不能解决这个问题。

Any suggestions? 有什么建议么?

If you want a count of the values where the OTHER column is 3, then a UNION would work like this: 如果要对OTHER列为3的值进行计数,那么UNION将像这样工作:

SELECT value, theCount = COUNT(*)
FROM (
    SELECT value = col1
    FROM scores
    WHERE col2 = 3
    UNION ALL
    SELECT col2
    FROM scores
    WHERE col1 = 3) T
GROUP BY value
ORDER BY value;

One way is using case: 一种方式是使用案例:

SELECT 
  case Col1 when 3 then Col2 else Col1 end,
  count(*) 
FROM scores 
WHERE Col1 = 3 OR Col2 = 3
Group by
  case Col1 when 3 then Col2 else Col1 end;

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

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