数据库MySQL的
以下是create table语句。
CREATE TABLE `Test`( `T` varchar(40) DEFAULT NULL,`P` varchar(40) NOT NULL,`CT` char(1) DEFAULT 'V',`XY` char(1) DEFAULT 'A');
在上表中有3列(T,P,CT,XY)。 1.在专栏' T'和专栏' P'具有这样的关系,即两列的值将成对。该对中的任何值都不会与其他列的其他值配对。 2.列CT有3种可能的值---> V,W,X。 3.列XY具有3种可能的值---> A,B,C。
表中的数据如下。
1. insert into Test values('T1','P1','V','A');
2. insert into Test values('T1','P2','V','B');
3. insert into Test values('T2','P3','V','C');
4. insert into Test values('T3','P3','V','A');
5. insert into Test values('T4','P4','V','A');
6. insert into Test values('T4','P4','V','A');
7. insert into Test values('T4','P4','V','B');
8. insert into Test values('T4','P4','W','A');
9. insert into Test values('T4','P4','X','A');
输出只有一行 - T4,P4,2
解释
1. First row will be discarded because of T1 is making pair with 2 values(P1,P2)of Column 'P'.
2. Second row will be discarded because of T1 is making pair with 2 values(P1,P2)of Column 'P'.
3. Third row will be discarded because of P3 is making pair with 2 values(T2,T3)of Column 'T'.
4. Fourth row will be discarded because of P3 is making pair with 2 values(T2,T3)of Column 'T'.
5. Output will be pair of T4,P4
对于一对(T4,P4),将导出第三列输出,计算列' CT'的实例数。值为V,列为' XY'值为A.有2个实例(你可以在第5行和第6行看到),所以输出的第3列将是2.
我尝试使用查询,但它没有给我正确的结果。
select T,P,sum from (select T,P,sum(if(CT = 'A' and XY = 'B',1,0)) sum from Test group by T,P ) X group by T having count(*)=1;
什么是Sql Query来解决上述问题?
答案 0 :(得分:0)
通过使用汇总查询来查找和排除T
或P
在所有独特组合中重复的情况,可以满足您对输出生成方式的解释中的前四项。 T
和P
,就像在此处的子查询中所做的那样:
select
t.T, t.P, count(*) as rows
from
Test as t
left join (
select T from (select distinct T, P from Test) as p1 group by T having count(*) > 1
) as dupT on dupT.T=t.T
left join (
select P from (select distinct T, P from Test) as p2 group by P having count(*) > 1
) as dupP on dupP.P=t.P
where
dupT.T is null
and dupP.P is null
and CT = 'V'
and XY = 'A'
group by
t.T, t.P;
这是对您的标准的完全字面解释,丢弃不良数据,但您也可以通过包含仅包含好数据来实现这一点:
select
t.T, t.P, count(*) as rows
from
Test as t
inner join (
select T from (select distinct T, P from Test) as p1 group by T having count(*) = 1
) as dupT on dupT.T=t.T
inner join (
select P from (select distinct T, P from Test) as p2 group by P having count(*) = 1
) as dupP on dupP.P=t.P
where
CT = 'V'
and XY = 'A'
group by
t.T, t.P;