SQL查询与组和拥有

时间:2016-03-16 13:26:13

标签: sql sql-server performance

我尝试选择TypeId等于1而不是TypeId等于3的所有客户ID。

表示例:

---------------------
| ClientID | TypeId |
---------------------
|     1    |    1   |
|     1    |    3   |
|     2    |    3   |
|     3    |    1   |
---------------------

我的查询:

SELECT ClientId, TypeId
FROM Table
GROUP BY ClientId, TypeId
HAVING TypeId != 3

我有什么:

---------------------
| ClientID | TypeId |
---------------------
|     1    |    1   |
|     3    |    1   |
---------------------

我的期望:

---------------------
| ClientID | TypeId |
---------------------
|     3    |    1   |
---------------------

关键是该表有超过3 * 10 ^ 8个寄存器。

提前致谢!

4 个答案:

答案 0 :(得分:4)

我建议汇总和having

SELECT ClientId
FROM Table
GROUP BY ClientId
HAVING SUM(CASE WHEN TypeId = 1 THEN 1 ELSE 0 END) > 0 AND
       SUM(CASE WHEN TypeId = 3 THEN 1 ELSE 0 END) = 0;

HAVING子句中的每个条件都计算具有特定TypeId值的行数。 > 0表示至少有一个。 = 0表示没有。

如果您确实希望获得匹配的原始,那么所有TypeId与客户端相关联。您可以使用JOIN或窗口函数:

SELECT ClientId, TypeId
FROM (SELECT ClientId, TypeId,
             SUM(CASE WHEN TypeId = 1 THEN 1 ELSE 0 END) OVER (PARTITION BY ClientId) as TypeId_1,
             SUM(CASE WHEN TypeId = 3 THEN 1 ELSE 0 END) OVER (PARTITION BY ClientId) as TypeId_3
      FROM Table
     ) t
WHERE TypeId_1 > 0 AND TypeId_3 = 0;

答案 1 :(得分:2)

试试这个:

SELECT t1.* 
FROM Table AS t1
WHERE TypeId = 1 AND 
      NOT EXISTS (SELECT 1
                  FROM Table AS t2
                  WHERE t1.ClientId = t2.ClientId AND t2.TypeId = 3)

答案 2 :(得分:1)

试试这个

SELECT ClientId, TypeId
FROM Table
WHERE ClientId not in (select ClientId from Table where TypeId = 3)
GROUP BY ClientId, TypeId

答案 3 :(得分:1)

我认为您也可以使用公用表表达式实现此目的:

<div id="map_canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>

或者,试试这个:

@Component({
  selector: 'my-app',
  template: `
      <my-component
          [myAttr]="myAttr"
      ></my-component>
      <button (click)="onClick()">Click</button>
  `,
  directives: [MyComponent]
  })
  class AppComponent {
     myAttr: number = 1;

  onClick() {
      this.myAttr += 1;
  }
}