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”,即Total列,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同时具有Snumberas123和 not as 的情况下返回行123

返回的数据如下

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

现在无法保证特定 ID 的 Snumber 始终为 123,因此我不能使用左连接或右连接。如何解决这个泥潭?傻傻的

4

3 回答 3

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

在这里拉小提琴。

于 2013-10-15T07:15:05.763 回答
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

于 2013-10-15T07:14:52.403 回答
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
于 2013-10-16T06:45:11.893 回答