SQL查询以查找至少具有2个男性和2个女性孩子的记录

时间:2018-11-09 08:50:05

标签: sql self-join

在一次采访中,我被要求找出父母中至少有一个性别的孩子的父母的名字,即至少有1名男性和1名女性。我解决了然后,他们修改了问题,以查找至少有2个男性和2个女性孩子的父母的姓名。这是表: Table Name: Children

这是我第一次询问的查询:

SELECT distinct C1.Parent_Name 
FROM Children C1 
JOIN Children C2
  ON C1.Parent_Name = C2.Parent_Name
WHERE C1.Child_Gender = 'Male' AND C2.Child_Gender = 'Female';

请问第二个询问是否可以帮助您?

3 个答案:

答案 0 :(得分:4)

您可以尝试在HAVING中使用条件汇总功能

模式(MySQL v5.7)

CREATE TABLE T(
   Parent_Name VARCHAR(50),
  Child_Gender varchar(50)
);

INSERT INTO T VALUES('David','Male');
INSERT INTO T VALUES('Emma','Male');
INSERT INTO T VALUES('David','Female');
INSERT INTO T VALUES('David','Female');
INSERT INTO T VALUES('Tom','Female');
INSERT INTO T VALUES('N','Male');
INSERT INTO T VALUES('A','Male');
INSERT INTO T VALUES('K','Male');
INSERT INTO T VALUES('David','Female');
INSERT INTO T VALUES('Emma','Female');
INSERT INTO T VALUES('Emma','Female');
INSERT INTO T VALUES('Emma',null);
INSERT INTO T VALUES('J','Male');
INSERT INTO T VALUES('D','Male');
INSERT INTO T VALUES('Emma','Male');

查询#1

Select
    Parent_Name
From Children  
GROUP BY
    Parent_Name
HAVING  
    COUNT(CASE WHEN Child_Gender='Male' THEN 1 END)>1
AND 
    COUNT(CASE WHEN Child_Gender='Female' THEN 1 END) > 1;

| Parent_Name |
| ----------- |
| Emma        |

View on DB Fiddle

答案 1 :(得分:0)

仅对查询(>= 2而不是>= 1进行了少量更改:

SELECT parent_Name
FROM T  
GROUP BY parent_Name
HAVING COUNT(CASE WHEN Child_Gender = 'Male' THEN 1 END) >= 2
AND COUNT(CASE WHEN Child_Gender = 'Female' THEN 1 END) >= 2;

答案 2 :(得分:0)

在SQL Server中,您可以使用这种解决方案不仅获得人员,而且获得有关孩子的详细信息。

WITH CTE AS (

SELECT PivotTable.Parent_Name, 
       PivotTable.Female As nr_of_female_children,
       PivotTable.Male As nr_of_male_children
FROM
(SELECT #T.Parent_Name, #T.Child_Gender
    FROM #T) AS SourceTable
PIVOT
(
COUNT(Child_Gender)
FOR Child_Gender IN (Male,Female)
) AS PivotTable

)

SELECT *
FROM CTE
WHERE CTE.nr_of_female_children>1 AND CTE.nr_of_male_children >1