0

首先,我想说的是,我仍然是编写 SQL 查询的新手。我彻底搜索了有关此错误的答案,并且得到了很多答案,但似乎没有任何帮助,或者我会说我真的不知道如何将解决方案应用于我的。

这是我的挑战,我有一个应用程序表,它存储具有一些唯一列的申请人记录,例如(dl_number、parent_id、person_id)。parent_id 使用他/她的第一条记录跟踪个人申请人的历史记录,并且每个申请人都应该有一个唯一的 dl_number,但由于某些原因,一些申请人的 dl_number(s) 不是唯一的,因此需要用更改 dl_number(s)。

下面是 SQL 查询,它得到 [sql 错误 (1241) 操作数应包含 1 列] 错误。

SELECT id,application_id,dl_number,surname,firstname,othername,birth_date,status_id,expiry_date,person_id,COUNT(DISTINCT(dl_number,parent_id,birth_date)) AS NumOccurrences
FROM tbl_dl_application
WHERE status_id > 1
GROUP BY dl_number,parent_id,birth_date
HAVING NumOccurrences > 1

请有关如何解决此问题或解决此问题的更好方法的任何帮助。

样本表和预期结果

4

2 回答 2

0
**You have to use only one column while use to DISTINCT function. You used this three field dl_number,parent_id,birth_date. Just use 1 filed from these 3. Then query will run.**

例如。

SELECT id,application_id,dl_number,surname,firstname,othername,birth_date,status_id,expiry_date,person_id,COUNT(DISTINCT(parent_id)) AS NumOccurrences
FROM tbl_dl_application
WHERE status_id > 1
GROUP BY dl_number,parent_id,birth_date
HAVING NumOccurrences > 1
于 2016-08-17T08:40:03.440 回答
0

DISTICT 并不是真正以这种方式使用的功能。您可以SELECT DISTICT column1, column2 FROM table只获取唯一行,或者类似SELECT column, count(DISTINCT anothercolumn) FROM table GROUP BY column地获取组内的唯一行。

据我了解的问题:您在表中查找重复项。重复定义为这 3 列的值相同dl_n‌​umberparent_idbirth‌​_date

我还假设这id是您表中的主键。如果不是,请将t2.id <> t.id条件替换为唯一标识您的行的条件。

如果您只想知道重复的组是什么,这应该可以:

SELECT dl_n‌​umber, parent_id, birth‌​_date, count(*) as NumOccurences  -- You can only add aggregation functions here, not another column unless you group by it.
FROM tbl_dl_application t
WHERE status_id > 1 -- I don't know what this is but it should do no harm.
GROUP BY dl_n‌​umber, parent_id, birth‌​_date
HAVING count(*)>1

但是,如果您想了解每个重复行的详细信息,此查询将为您提供:

SELECT *
FROM tbl_dl_application t
WHERE 
    status_id > 1 -- I don't know what this is but it should do no harm.
    AND EXISTS (
        SELECT 1 
        FROM tbl_dl_application t2
        WHERE
            t2.dl_number = t.dl_number
            AND t2.parent_id = t.parent_id
            AND t2.birth_date = t.birth_date
            AND t2.id <> t.id
    )
ORDER BY dl_n‌​umber, parent_id, birth‌​_date, id;  -- So you have your duplicates nicely next to each other.

如果我误解了您的目标,请进一步解释,或者询问解决方案是否不够清楚。

于 2016-08-17T08:35:23.950 回答