SQL查询:如何过滤列中的每组值?

时间:2014-08-18 01:56:47

标签: mysql sql sql-server

目前我正在使用SQL Fiddle来插入以下声明。

CREATE TABLE table1
(
rn int,
pc varchar(25),
pc1 varchar(25),
grp varchar(25),
e_id varchar(25)
);

INSERT INTO table1
(rn, pc, pc1, grp, e_id)
VALUES(111, 'A1', 'A1', '175', '100');

INSERT INTO table1
(rn, pc, pc1, grp, e_id)
VALUES(111, 'A1', 'A1', '100', '90');

INSERT INTO table1
(rn, pc, pc1, grp, e_id)
VALUES(112, 'B1', 'B1', '101', '90');

INSERT INTO table1
(rn, pc, pc1, grp, e_id)
VALUES(112, 'B1', 'B1', '100', '90');

INSERT INTO table1
(rn, pc, pc1, grp, e_id)
VALUES(112, 'B1', 'B1', '100', '90');

INSERT INTO table1
(rn, pc, pc1, grp, e_id)
VALUES(113, 'C1', 'C1', '100', '90');

**As you can see there are 2 distinct rn numbers.**

    select *
    from table1 
    where rn in(select rn from table1 group by rn having count(*)>1)
    AND (pc = pc1)
    AND grp in (select max(grp) from table1)
    AND e_id in( select min(e_id) from table1)

我当前的查询能够根据条件

找到正确的行

QN:如何使条件适用于每组rn?

因此结果shld有一行111和112行。

我试过搜索foreach但找不到一个好的解决方案。

** QN2:我添加了一行,只有一个rn。我输出的前一个qns应为

RN  PC  PC1 GRP E_ID
111 A1  A1  175 100
112 B1  B1  101 90
113 C1  C1  100 90 --> this row with 1 rn should also output

3 个答案:

答案 0 :(得分:0)

也许这就是你想要的:

select rn, grp, e_id
from table1 
where rn in (select rn from table1 group by rn having count(*)>1)
AND (pc = pc1)
GROUP BY rn
HAVING grp = max(grp) AND e_id = min(e_id)

请参阅http://sqlfiddle.com/#!2/2d6a5/14

答案 1 :(得分:0)

SELECT * from table1
WHERE  pc = pc1
group by rn having max(grp) AND min(e_id)

sqlfiddle link

但我不确定你想要什么,因为最大GRP和min E_ID是不同的记录,我假设优先级是max grp跟随min e_id。

不使用

查询2
SELECT * from table1
WHERE  pc = pc1
group by rn
order by rn, grp asc, e_id desc

答案 2 :(得分:0)

select rn, max(pc),max(pc1),max(grp),max(e_id) 
from table1 
group by rn;

自'90'> '100'你需要强制转换 - 例如 - int如果你想要“最大”的那个:

select rn, max(pc),max(pc1),max(grp),max(cast(e_id as int)) 
from table1 
group by rn;

+------+---------+----------+----------+------------------------+
| rn   | max(pc) | max(pc1) | max(grp) | max(cast(e_id as int)) |
+------+---------+----------+----------+------------------------+
|  111 | A1      | A1       | 175      |                    100 |
|  112 | B1      | B1       | 101      |                     90 |
|  113 | C1      | C1       | 100      |                     90 |
+------+---------+----------+----------+------------------------+

根据“重复”行的内容选择聚合函数(例如max)。