我有下表。
CREATE TABLE "questions"
("counter" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE ,
"questionid" INTEGER NOT NULL ,
"chapter" INTEGER NOT NULL ,
"image" VARCHAR NOT NULL )
我想得到这个:
CHAPTER, NUMBER OF QUESTIONS IN CHAPTER, NUMBER OF IMAGES IN CHAPTER
我设法用 UNION 得到了结果,但这不符合我上面的要求(即我有 2 列的输出,而不是 3 列)!
// First query: get only chapters with images, and count all questions
SELECT Q1.chapter as "chapterID with images", count(q1.image) as c1
FROM questions AS Q1
where q1.chapter IN (SELECT chapter from questions where image NOT LIKE "")
group by q1.chapter
UNION
// Second query: get only chapters with images and count only images
SELECT Q2.chapter as "chapterID with images", count(q2.image) as c2
FROM questions AS Q2
WHERE Q2.image NOT LIKE ""
group by q2.chapter
尝试使用单个查询我只能得到第一个 COUNT 或第二个,例如如下。
// NOT WORKING!
SELECT Q1.chapter as "chapterID with images", count(q1.image), count (q2.image)
FROM questions AS Q1, questions AS Q2
where q1.chapter IN (SELECT chapter from questions where IMAGE NOT LIKE "")
AND q1.counter= q2.counter
group by q1.chapter
非常感谢。
更新:解决方案
按照 LS_dev 建议的方法,我解决了如下问题。
我现在想从 2 个子查询中获取值并将它们分开(即图像/问题),但它不起作用,但我知道这是一个不同的问题......
SELECT chapter,
(SELECT COUNT(*) FROM questions WHERE chapter=Q1.Chapter AND image NOT LIKE "" ) as "number of images",
(SELECT COUNT(*) FROM questions WHERE chapter=Q1.Chapter) as "number of questions"
FROM questions AS Q1
WHERE chapter in (SELECT chapter from questions where IMAGE NOT LIKE "")
GROUP BY chapter