我在MySQL表中有以下数据。
+--------+----------+------+
| job_id | query_id | done |
+--------+----------+------+
| 15145 | a002 | 1 |
| 15146 | a002 | 1 |
| 15148 | a002 | 1 |
| 15150 | a002 | 1 |
| 15314 | a003 | 0 |
| 15315 | a003 | 1 |
| 15316 | a003 | 0 |
| 15317 | a003 | 0 |
| 15318 | a003 | 1 |
| 15319 | a003 | 0 |
+--------+----------+------+
我想知道是否有可能有一个SQL查询,可以按query_id分组如果所有'完成'字段标记为1 。我想象的可能输出是:
+----------+------+
| query_id | done |
+----------+------+
| a002 | 1 |
| a003 | 0 |
+----------+------+
我尝试过以下SQL查询:
select job_id, query_id, done from job_table group by done having done = 1 ;
但没有运气。我真的很感激你的帮助!
答案 0 :(得分:4)
我并不为这个解决方案感到特别自豪,因为它不是很清楚,但至少它快速而简单。如果所有项目都“done”= 1 ,则总和将等于计数SUM = COUNT
SELECT query_id, SUM(done) AS doneSum, COUNT(done) AS doneCnt
FROM tbl
GROUP BY query_id
如果你添加一个having子句,你会得到“完成”的项目。
HAVING doneSum = doneCnt
我会让你正确地格式化解决方案,你可以做一个分歧来获得“未完成”的项目或doneSum<> doneCnt。
顺便说一句,SQL小提琴here。
答案 1 :(得分:0)
所有“完成”工作:
<body>
<ul>
<li>Foo</li>
<li>Bar</li>
<li>Baz</li>
<li>Qux</li>
</ul>
</body>
所有“未完成”的工作:
SELECT * FROM job_table GROUP BY done HAVING MIN(done) = 1;
所有具有相同值的作业(“完成”或“撤消”):
SELECT * FROM job_table GROUP BY done HAVING MAX(done) = 0;
答案 2 :(得分:0)
您的示例中的输出可以通过以下方式获得:
SELECT query_id, min(done) as done
FROM job_table
GROUP by done
答案 3 :(得分:-1)
我认为你应该看看这个
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
答案 4 :(得分:-1)
尝试类似
的内容SELECT qry_id, 1
FROM (
SELECT qry_id, done
FROM tbl
GROUP BY qry_id, done
) AS t
GROUP BY qry_id
HAVING COUNT(*)=1
UNION
SELECT qry_id, 0
FROM (
SELECT qry_id, done
FROM tbl
GROUP BY qry_id, done
) AS t
GROUP BY qry_id
HAVING COUNT(*)>1