我有下表。Sqlite:單個查詢與2不同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
非常感謝。
UPDATE:解決方案
繼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'添加列,但不適合您的問題。 –
我知道,是的,但謝謝你的評論。 – MDT