【发布时间】:2013-09-29 18:42:51
【问题描述】:
我有下表。
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
【问题讨论】:
-
UNION总是添加行。JOIN添加列,但不适合您的问题。 -
我知道,是的,但感谢您的评论。
标签: sql sqlite join count union