Sqlite:不使用UNION的2个不同COUNT的单个查询

时间:2013-09-24 13:48:39

标签: sql sqlite join count union

我有下表。

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

1 个答案:

答案 0 :(得分: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;