0

我有下表。

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
4

1 回答 1

4

该问题最适合子查询,因为需要不同的计数:

 SELECT chapter, COUNT(),
    (SELECT COUNT() FROM questions WHERE chapter=q1.Chapter AND image NOT LIKE "")
    FROM question AS q1 GROUP BY chapter;

编辑:允许更多操作:

CREATE VIEW sums_view AS SELECT chapter, COUNT() AS question_count,
    (SELECT COUNT() FROM questions WHERE chapter=q1.Chapter AND image NOT LIKE "") AS image_count
    FROM question AS q1 GROUP BY chapter;

现在,以前的查询可以用作表:

 SELECT * FROM sums;

并且可以进行一些mora操作:

 SELECT *, image_count*100.0/question_count AS image_ratio FROM sums_view;
于 2013-09-24T13:55:00.903 回答