GROUP BY WITH HAVING ( DISTINCT ) : PHP , MYSQL
GROUP BY WITH HAVING ( DISTINCT ) : PHP , MYSQL
id | mid | pid | owgh | nwgh |
1 3 12 1.5 0.6
2 3 12 1.5 0.3
3 3 14 0.6 0.4
4 3 15 1.2 1.1
5 4 16 1.5 1.0
6 4 17 2.4 1.2
7 3 19 3.0 1.4
从上面我想要 nwgh 的 mid AND SUM 及其 resp 的总数。 ID 例如:mid=3 或 mid=4
但是使用 DISTINCT pid 但请注意 nwgh 的总和不应该是 DISTINCT
因此我的结果如下:
mid | countmid | totalnwgh
3 4 (DISTINCT value) 3.8 (no DISTINCT it take both value of pid =12)
4 2 2.2
在上面的结果中,mid = 3 的计数为 4,因为 pid = 12 被重复,因此它是 DISTINCT 但 nwgh 不应该是 DISTINCT,它的总计数
我试过的
Select mid , COUNT(mid) as countmid , SUM(nwgh) as totalnwgh from test where mid = 3
GROUP BY mid HAVING count(DISTINCT pid)
如果我明白你想要什么,你只需要在 COUNT 中做一个 distinct。
你可以试试这个:
SELECT mid ,
COUNT(distinct pid) as countmid ,
SUM(nwgh) as totalnwgh
FROM test
GROUP BY mid
如果需要,试试这个 sqlfiddle:http://sqlfiddle.com/#!9/45e68/2
使用这个
SELECT a.`mid`, a.cnt AS countmid, b.s AS totalnwgh
FROM
(SELECT `mid`, COUNT(DISTINCT pid) AS cnt FROM test GROUP BY 1) AS a INNER JOIN
(SELECT `mid`, SUM(nwgh) AS s FROM test GROUP BY 1) b ON a.mid=b.mid
id | mid | pid | owgh | nwgh |
1 3 12 1.5 0.6
2 3 12 1.5 0.3
3 3 14 0.6 0.4
4 3 15 1.2 1.1
5 4 16 1.5 1.0
6 4 17 2.4 1.2
7 3 19 3.0 1.4
从上面我想要 nwgh 的 mid AND SUM 及其 resp 的总数。 ID 例如:mid=3 或 mid=4 但是使用 DISTINCT pid 但请注意 nwgh 的总和不应该是 DISTINCT
因此我的结果如下:
mid | countmid | totalnwgh
3 4 (DISTINCT value) 3.8 (no DISTINCT it take both value of pid =12)
4 2 2.2
在上面的结果中,mid = 3 的计数为 4,因为 pid = 12 被重复,因此它是 DISTINCT 但 nwgh 不应该是 DISTINCT,它的总计数
我试过的
Select mid , COUNT(mid) as countmid , SUM(nwgh) as totalnwgh from test where mid = 3
GROUP BY mid HAVING count(DISTINCT pid)
如果我明白你想要什么,你只需要在 COUNT 中做一个 distinct。
你可以试试这个:
SELECT mid ,
COUNT(distinct pid) as countmid ,
SUM(nwgh) as totalnwgh
FROM test
GROUP BY mid
如果需要,试试这个 sqlfiddle:http://sqlfiddle.com/#!9/45e68/2
使用这个
SELECT a.`mid`, a.cnt AS countmid, b.s AS totalnwgh
FROM
(SELECT `mid`, COUNT(DISTINCT pid) AS cnt FROM test GROUP BY 1) AS a INNER JOIN
(SELECT `mid`, SUM(nwgh) AS s FROM test GROUP BY 1) b ON a.mid=b.mid