【问题标题】:i need make a count(*) of two elements of the same column我需要对同一列的两个元素进行计数(*)
【发布时间】:2022-12-19 18:48:30
【问题描述】:

我有以下问题,在我的数据库中有两个表:

表A:

| Column A | Column B | Column c | Column d |
| 1        | 01/22    | add      |    0     |
| 2        | 01/20    | del      |    1     |
| 3        | 01/22    | add      |    1     |
| 4        | 01/21    | del      |    1     |
| 5        | 01/21    | add      |    2     |
| 6        | 01/21    | del      |    2     |

表B:

| Column A | Column B | Column c | Column d | Column e |
| 1        | 01/22    | add      |    0     | 0        |
| 2        | 01/20    | del      |    1     | 1        |
| 3        | 01/22    | add      |    1     | 0        |
| 4        | 01/21    | del      |    1     | 1        |
| 5        | 01/21    | add      |    2     | 0        |
| 6        | 01/21    | del      |    2     | 1        |

现在需要将此表的并集转换为下一个形式:

选择 count(a.Column a), count(b.Column e = 1) 1, count(b.Column e = 0) 0, column B from tableA a, tableB b where a.column d = b.column d group通过 a.B 列;

有些像这样。我不确定向我解释

我需要将 e 列分成两个不同的部分并进行计数。 到这种形式:

| count(a.Column a) | count(1) | count(0)| column B |
| 1                 | 1        | 0       |    01/20 | 
| 3                 | 2        | 1       |    01/21 | 
| 2                 | 0        | 2       |    01/22 | 

【问题讨论】:

  • 使用条件聚合:COUNT(CASE WHEN b.[Column e] = 1 THEN 1 END) AS Count_1, COUNT(CASE WHEN b.[Column e] = 0 THEN 1 END) AS Count_0。 CASE 语句将生成值 (1) 或 NULL(隐式 ELSE 默认值)。 COUNT() 只计算非空值。您可以查看的另一个功能是 PIVOT

标签: sql sql-server database oracle count


【解决方案1】:

好的,我使用以下方法找到了解决方案:

sum(case when b.Column e = 0 then 1 else 0 end) as 0,
sum(case when b.Column e > 0 then 1 else 0 end) as 1

选择count(a.Column a), sum(case when b.Column e = 0 then 1 else 0 end) as 0, sum(case when b.Column e > 0 then 1 else 0 end) as 1, B列表A a,表B b在哪里a.d 列 = b.d 列团体 经过a.B栏;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多