2013-10-15 54 views
2

這是我的問題的簡化版本。使用連接檢索匹配行

我有表像下面

Id Name  SNumber 
100 XYZ  123 
100 XYZ  123 
101 ABC  123 
103 QAZ  123 
100 XYZ  971 
100 XYZ  872 
100 XYZ  659 
102 PQR  145 
102 PQR  707 
103 QAZ  421 

我想指望有Snumber爲 '123' 有Snumber即列和行的行不爲 '123',即otherTotal

Id Name  Total OtherTotal 
100 XYZ  2   3 
101 ABC  1   0 
102 PQR  0   2 
103 QAZ  1   1 

我在做什麼是使用連接

Select xx.*,otherTotal 
From 
    (Select Id,Name,count(*) as Total 
     From table 
     Where Snumber like '123' 
     Group By id,name 
    )xx 

Inner join 

    (Select Id,Name,count(*) as otherTotal 
     From table 
     Where Snumber not like '123' 
     Group By id,name 
    )yy 

On xx.Id=yy.Id 

但這隻會返回行,如果特定Id既有Snumber123而不是123

返回的數據是像下面

Id Name  Total OtherTotal 
100 XYZ  2   3 
103 QAZ  1   1 

現在還沒有guarntee一個特定的ID將永遠有Snumber爲123,所以我不能使用左或右連接。如何解決這個泥潭? Giggity

回答

4

試試這個:

SELECT id, name, 
    COUNT(CASE WHEN SNumber = 123 THEN 1 END) Total, 
    COUNT(CASE WHEN SNumber <> 123 THEN 1 END) OtherTotal 
FROM t 
GROUP BY id, name 
ORDER BY id 

小提琴here

3
select 
    Id, Name, 
    sum(case when SNumber = 123 then 1 else 0 end) as Total, 
    sum(case when SNumber <> 123 then 1 else 0 end) as OtherTotal 
from Table1 
group by Id, Name 
order by Id 

select 
    Id, Name, 
    count(*) - count(nullif(SNumber, 123)) as Total, 
    count(nullif(SNumber, 123)) as OtherTotal 
from Table1 
group by Id, Name 
order by Id 

sql fiddle demo

1

試試這個。

DECLARE @TABLE TABLE (ID INT, NAME VARCHAR(40), SNUMBER INT) 
INSERT INTO @TABLE 
VALUES 
(100 ,'XYZ',  123), 
(100 ,'XYZ',  123), 
(101 ,'ABC',  123), 
(103 ,'QAZ',  123), 
(100 ,'XYZ',  971), 
(100 ,'XYZ',  872), 
(100 ,'XYZ',  659), 
(102 ,'PQR',  145), 
(102 ,'PQR',  707), 
(103 ,'QAZ',  421) 

SELECT 
    ID, 
    NAME, 
    (
     SELECT 
      COUNT(SNUMBER) FROM @TABLE B 
     WHERE 
      SNUMBER = '123' AND A.ID = B.ID 
    ) AS TOTAL, 
    (
     SELECT 
      COUNT(SNUMBER) FROM @TABLE B 
     WHERE 
      SNUMBER <> '123' AND A.ID = B.ID 
    ) AS OTHERTOTAL 
FROM 
    @TABLE A 
GROUP BY ID, NAME