繁体   English   中英

SQL 子查询,使用 WHERE & 'IN' 过滤特定行

[英]SQL subquery , using WHERE & 'IN' to filter for specific rows

请使用此处并复制下面的代码以将上下文添加到我的问题中。

如您所见,我有一张桌子,里面有几个父亲的名字相同,我想选择拥有最多dogsfather作为我的最终名单。 您可以在Query #1看到整个表,我在Query #2想要的结果与Father's返回有关,但是当我试图让Query #3 John神父只返回 1 次时,它显示了父亲的整个记录约翰有 9 条狗和 10 条狗。

我怎样才能让Query #3只选择一个拥有 Max Dogs 的父亲,并返回其余的列?

创建表代码:

CREATE TABLE IF NOT EXISTS `table_3` 
(
    `id` int(6) unsigned NOT NULL,
    `Father` varchar(200) NOT NULL,
    `Dogs` varchar(200) NOT NULL,
    PRIMARY KEY (`id`)
);

INSERT INTO `table_3` (`id`,`Father`, `Dogs`) 
VALUES ('1', 'John', '10'),
       ('2', 'John','9'),
       ('3', 'Joe', '4'),
       ('4', 'Jeremy', '4'),
       ('5', 'Jack', '4'),
       ('6', 'NULL', '5');

查询#1

select Father from table_3;

查询 #1 输出:

id  Father  Dogs
1   John    10
2   John    9
3   Joe 4
4   Jeremy  4
5   Jack    4
6   NULL    5

查询#2

select b.Father from (select Father, max(Dogs)
from table_3
group by 1
)b;

查询 #2 输出

Father
Jack
Jeremy
Joe
John
NULL

查询 #3

select * from table_3 a
where a.Father in (
select b.Father from (select Father, max(Dogs)
from table_3 
group by 1
)b);

查询 #3 输出

id  Father  Dogs
1   John    10
2   John    9
3   Joe 4
4   Jeremy  4
5   Jack    4
6   NULL    5

查询 #3 的期望输出

id  Father  Dogs
1   John    10

3   Joe 4
4   Jeremy  4
5   Jack    4
6   NULL    5

尝试这个 -

SELECT * FROM table_3 A
INNER JOIN( 
    SELECT father,MAX(Dogs) Dogs 
    -- You need to CAST your Dogs column to INT before you apply MAX on this column
    FROM table_3
    GROUP BY Father
)B
ON A.father = B.father
AND A.Dogs = B.Dogs 

如果您的数据库允许,您也可以尝试使用行号,如下所示 -

SELECT * FROM (
    SELECT *,
    ROW_NUMBER() OVER (PARTITION BY father ORDER BY Dogs DESC) RN
    FROM table_3
) A WHERE RN = 1

用这个..

select * from table_3 group by Father order by Dogs

或者

SELECT id, Father, max(CONVERT(Dogs,SIGNED)) from table_3 group by Father

我认为以下代码可以帮助您使用 sql server:

SELECT Father,
   MAX(CONVERT(INT, Dogs))
FROM   table_3
GROUP BY
   father
ORDER BY
   MAX(CONVERT(INT, Dogs)) DESC

或者

SELECT DISTINCT Father,
   MAX(CONVERT(INT, Dogs)) OVER(PARTITION BY Father) AS avgsales
FROM   table_3

在 MySQL 中

改变:

CONVERT(INT, Dogs)

CAST(Dogs AS SIGNED)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM