sqlite SQL -如何从2列中找到唯一值?

r1zk6ea1  于 2022-12-27  发布在  SQLite
关注(0)|答案(3)|浏览(211)

我正在使用SQLite,并且希望只获取每个表中具有唯一值的行。我知道如何获取每个列的值,但无法创建一个(SQLite兼容)选择来获取两列的唯一值。
以下是数据示例:
| 列_A|列B|
| - ------| - ------|
| 一百一十一|七七七|
| 二百二十二|三百三十三|
| 二百二十二|一百一十一|
| 四四四|三百三十三|
| 二百二十二|五百五十五|
| 三百三十三|六六六|
| 三百三十三|七七七|
上例中我希望得到的结果是具有唯一值的行,这些值仅包括:四十四万五百五十五六百六十六
| 列_A|列B|
| - ------| - ------|
| * * 四百四十四
*|三百三十三|
| 二百二十二|* * 五百五十五人**|
| 三百三十三|* * 六百六十六**|
222不应出现在结果中,因为它在col_A中出现了多次。777不应出现在结果中,因为它在col_B中出现了多次。我只需要col_A或col_B中出现一次的值。每个表(而不是列)的值是唯一的。
我设法做到了什么程度:

SELECT * 
    FROM my_table
    WHERE 
        (SELECT col_A as asset from my_table GROUP BY col_A HAVING COUNT(*) = 1
         UNION
        SELECT col_B as asset from my_table GROUP BY col_B HAVING COUNT(*) = 1)
            IN (col_A, col_B)

我已经尝试了联合和其他几种方法,但无法达到预期的结果。

dldeef67

dldeef671#

要按UNION ALL开始过滤,请考虑关键字*******中的任意一个都是合适的选项沿着可与HAVING子句一起确定不同的值,例如

WITH t1 AS  
(
 SELECT col
   FROM (SELECT col_A AS col  FROM t UNION ALL
         SELECT col_B         FROM t) AS tt
  GROUP BY col
 HAVING COUNT(*)=1 
)
SELECT t.* 
  FROM t1
  JOIN t
    ON col IN ( col_A , col_B )

Demo

vaj7vani

vaj7vani2#

我认为您需要这样的查询:

;with unqs as (
  select col_c
  from (
    select col_c, count(col_c) cnt
    from (
      select col_A as col_c
      from my_table
      union all
      select col_B as col_c
      from my_table) as t
     group by col_c) as tt
  where cnt = 1
)
select *
from my_table
where col_A in (select col_c from unqs)
   or col_B in (select col_c from unqs);

SQL小提琴

qmelpv7a

qmelpv7a3#

WITH
  symetric AS
(
  SELECT col_a, col_b, col_a AS lookup FROM t
  UNION ALL
  SELECT col_a, col_b, col_b AS lookup FROM t
)
SELECT
  col_a, col_b
FROM
  symetric   AS t
WHERE
  NOT EXISTS (
    SELECT * 
      FROM symetric
     WHERE lookup          = t.lookup
       AND (col_a, col_b) <> (t.col_a, t.col_b)
  )
ORDER BY
  col_a, col_b

演示; https://dbfiddle.uk/9tzUASle

相关问题