SQL:修改具有唯一值的查询结果行

时间:2012-10-01 16:18:31

标签: sql sqlite

我有一个 sqlite 查询,返回类似以下内容的字符[letter,number]:

("a", 1) 
("a", 2)
("b", 3)
("c", 3)

如果字母不同,我想将数字列检索为0。怎么做?

预期产出:

("a", 1) 
("a", 2)
("b", 0)
("c", 0)

4 个答案:

答案 0 :(得分:1)

如何(SQL Fiddle):

SELECT Q.letter, 
    CASE WHEN (SELECT COUNT(*) FROM (query) QQ WHERE QQ.letter = Q.letter) = 1 THEN 0 
         ELSE Q.number
    END AS number
FROM (query) Q

注意,将“query”替换为生成第一个结果的查询。

答案 1 :(得分:1)

您可以使用子查询:

select t1.col1,
  case when t2.cnt > 1 then t1.col2 else 0 end col2
from table1 t1
left join
(
  select count(*) as cnt, col1
  from table1 
  group by col1
) t2
  on t1.col1 = t2.col1

请参阅SQL Fiddle with Demo

答案 2 :(得分:1)

SELECT tba.mychar
-- if tbu.mychar is null, then the letter is not unique
--   when it happens, the letter is not "unique" thus use the number column
--   else use zero for "unique" letters
, CASE WHEN tbu.mychar IS NULL THEN tba.mynum ELSE 0 END AS newnum
FROM mytab tba
LEFT JOIN (
    -- this subquery only returns the letters that don't repeat
    SELECT mychar
    FROM mytab
    GROUP BY mychar
    HAVING COUNT(*) = 1
) AS tbu ON tba.mychar=tbu.mychar

答案 3 :(得分:1)

可以使用UNION ALL 2个单独的语句(一个用于重复的字母,一个用于仅出现一次的字母):

    SELECT letter, number
    FROM tableName
    WHERE letter IN (
        SELECT letter
        FROM tableName
        GROUP BY letter
        HAVING COUNT(1) > 1
    )
UNION ALL
    SELECT letter, 0
    FROM tableName
    WHERE letter IN (
        SELECT letter
        FROM tableName
        GROUP BY letter
        HAVING COUNT(1) = 1
    )