Database-MySqlComplex sqlQuery
以下是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的實例數爲A.有2個實例(因爲您可以在第5行和第6行中看到),所以第三列輸出將是2.
I嘗試使用查詢,但它不是givi正確的結果。
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來解決上述問題?
你可以嘗試更簡單的解釋你如何選擇行嗎? –
也是一個更好的背景,它用於什麼目的。試圖使「通用」有時可以防止由於上下文的丟失。 – DRapp