1

我的桌子是,

 customdata check service loc value
  101        0    0        4   4
  101        0    0        3   3
  101        5     4       4    3
  102        0     0       1     2
  102        4     4       3     3
  103        0     0       4     4

我的结果应该是,

  customdata cnt splcnt//count of check when not 0
   101        3    1
   102        2    1
   103        1    0

谁能告诉我我应该如何让我的查询来计算这两个数。

4

2 回答 2

2

使用CASE语句有条件地SUM基于 的值check

SELECT
    customdata,
    COUNT(*) AS cnt,
    SUM(CASE WHEN check > 0 THEN 1 ELSE 0 END) AS splcnt
FROM YourTable
GROUP BY customdata
于 2012-10-01T21:28:41.053 回答
1

表名 = tcustomdata,检查 col 重命名为 chck

SELECT a.customdata, a.cnt AS CNT_ALL, c.cnt AS chckcnt
FROM (SELECT customdata, COUNT(*) AS cnt FROM tcustomdata GROUP BY customdata) a
LEFT OUTER JOIN 
(SELECT customdata, COUNT(*) AS cnt FROM tcustomdata WHERE chck != 0 GROUP BY customdata) c
ON a.customdata = c.customdata

sql fiddle上查看

于 2012-10-01T21:37:25.463 回答