简体   繁体   中英

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 ). 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)

+-------+-------+
| 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.

Any suggestions?

If you want a count of the values where the OTHER column is 3, then a UNION would work like this:

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;

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