建议需要编写一个复杂的查询 - sqlite

时间:2013-05-24 05:16:01

标签: sqlite

我在名为musics的表格中有4列 - 'artist','genre', 'writer' , 'producer'.

我需要编写一个查询,如果没有重复与列名对应的值,则返回值0;如果重复值,则应返回值1,对应于该列名。

非常感谢任何帮助

4 个答案:

答案 0 :(得分:2)

Artist

select convert(bit,(count(1)-1))
from table_name
group by artist  -- <-- Replace artist with column name for which duplicate

答案 1 :(得分:2)

SELECT (COUNT(artist)   <> COUNT(DISTINCT artist))   artist,
       (COUNT(genre)    <> COUNT(DISTINCT genre))    genre,
       (COUNT(writer)   <> COUNT(DISTINCT writer))   writer,
       (COUNT(producer) <> COUNT(DISTINCT producer)) producer
FROM musics

另一个版本

SELECT 
( SELECT (COUNT(*) > 0) 
    FROM (SELECT 1 FROM musics GROUP BY artist HAVING COUNT(*) > 1) a 
) artist,
( SELECT (COUNT(*) > 0) 
    FROM (SELECT 1 FROM musics GROUP BY genre HAVING COUNT(*) > 1) g 
) genre,
( SELECT (COUNT(*) > 0) 
    FROM (SELECT 1 FROM musics GROUP BY writer HAVING COUNT(*) > 1) w 
) writer,
( SELECT (COUNT(*) > 0) 
    FROM (SELECT 1 FROM musics GROUP BY producer HAVING COUNT(*) > 1) p 
) producer

示例数据

|  artist |  genre |  writer |  producer |
------------------------------------------
| artist1 | genre1 | writer1 | producer1 |
| artist2 | genre2 | writer1 | producer2 |
| artist1 | genre3 | writer3 | producer3 |

示例输出:

| artist | genre | writer | producer |
--------------------------------------
|      1 |     0 |      1 |        0 |

<强> SQLFiddle

答案 2 :(得分:1)

使用带有指定列的distinct和另一个没有distinct的select count来编写select count语句,并根据您的要求比较它们

答案 3 :(得分:1)

你可以使用4个不同的查询与union&amp;每个查询必须包含count(列名)+ group by子句