根据多列中的条件计算不同的值

时间:2016-03-10 05:09:43

标签: sql-server count distinct

我有一个这样的表,我想从中计算每个用户名的重复次数。我想计算每个用户Type有多少不同的Amount <> 0

+----------+-------------+--------+
| Username |    Type     | Amount |
+----------+-------------+--------+
| abc      | New         |      1 |
| abc      | New         |      1 |
| abc      | Old         |      1 |
| def      | New         |      1 |
| def      | Old         |      0 |
| def      | Refurbished |      1 |
| ijk      | New         |      1 |
| ijk      | Old         |      2 |
| ijk      | Refurbished |      3 |
+----------+-------------+--------+

我的结果应该是这样的:

+----------+---------------+
| Username | DistinctCount |
+----------+---------------+
| abc      |             2 |
| def      |             2 |
| ijk      |             3 |
+----------+---------------+

..其中[Username] abc 2 distinct [Type] [Amount] not equal to 0 {。}}。

我尝试了SELECT DISTINCT Type, Username, SUM(CASE WHEN Amount <> 0 THEN 1 ELSE 0 END) FROM tblBase GROUP BY Type, Username,但它没有产生预期的结果。

3 个答案:

答案 0 :(得分:4)

COUNT DISTINCTCASE

一起使用
SELECT
    Username,
    DistinctCount = COUNT(DISTINCT CASE WHEN Amount <> 0 THEN Type END)
FROM #tbl
GROUP BY Username;

使用WHERE子句的区别在于,这将返回0 DistinctCount的行,而WHERE子句则不会。

DEMO

答案 1 :(得分:3)

根据您的输出,您需要每个用户名一行。这意味着您希望按用户名分组。您希望按用户名计算不同类型的数量,并且有一个聚合函数。试试这个:

mysql> SELECT *, (SELECT MAX(m2.update_time) FROM maria_bug m2 WHERE m1.id <> 0 ) max_update FROM maria_bug m1;
+----+----------------------------+----------------------------+
| id | update_time                | max_update                 |
+----+----------------------------+----------------------------+
|  1 | 2001-01-01 00:00:00.200000 | 2001-01-01 00:00:00.200000 |
|  1 | 2001-01-01 00:00:00.100000 | 2001-01-01 00:00:00.000000 |
+----+----------------------------+----------------------------+
2 rows in set (0.00 sec)

答案 2 :(得分:3)

plunker2

我想说,使用Amount&lt;&gt; SELECT Username, COUNT(DISTINCT Type) AS DistinctCount FROM tblBase WHERE Amount <> 0 GROUP BY Username 中的0和使用用户名的Where并使用group by获取计数