我的 SQL 表是這樣設定的:
- 鍵(主鍵)
- 父鍵(一個父鍵的多個主鍵)
- 點 1
- 點 2
- 修飾符
修改器確定對總分的影響。IE
- 修改器 A - 總分 =(點 1 點 2)*0.1
- 修改器 B - 總分 =(點 1 點 2)*0.2
- 修飾符 C - 總點數 = (點數 1 點數 2)*0.7
理想情況下,我想制作一張表格:
- 父鍵
- 該鍵的總修改點數(例如 100 * 0.2 150 * 0.5 180 * 0.7)
我無法讓它為我的生活作業。我最接近的是下面的代碼,它為每個父鍵輸出一行,為每個修飾符輸出一列。但是,盡管這些陳述句都單獨產生了我想要的值,但每一列都填充了一個值。
SELECT table.parent, t1.one, t1.two, t1.three
FROM
table
LEFT JOIN
(SELECT
(SELECT ((sum(points1) sum(points2))*0.1) FROM table WHERE (modifier = "modifier one") GROUP BY key) as 'one',
(SELECT ((sum(points1) sum(points2))*0.2) FROM table WHERE (modifier = "modifier two") GROUP BY key) as 'two',
(SELECT ((sum(points1) sum(points2))*0.7) FROM table WHERE (modifier = "modifier three") GROUP BY key) as 'three'
) t1
GROUP BY table.parent
uj5u.com熱心網友回復:
您可以使用條件聚合來做到這一點:
SELECT parent,
SUM((points1 points2) * CASE WHEN modifier = 'modifier one' THEN 0.1 ELSE 0 END) one,
SUM((points1 points2) * CASE WHEN modifier = 'modifier two' THEN 0.2 ELSE 0 END) two,
SUM((points1 points2) * CASE WHEN modifier = 'modifier three' THEN 0.7 ELSE 0 END) three
FROM tablename
GROUP BY parent;
或者,使用TOTAL()聚合函式:
SELECT parent,
0.1 * TOTAL((points1 points2) * (modifier = 'modifier one')) one,
0.2 * TOTAL((points1 points2) * (modifier = 'modifier two')) two,
0.7 * TOTAL((points1 points2) * (modifier = 'modifier three')) three
FROM tablename
GROUP BY parent;
或者,如果您的 SQLite 版本是 3.30.0 ,則使用以下FILTER子句:
SELECT parent,
0.1 * TOTAL(points1 points2) FILTER (WHERE modifier = 'modifier one') one,
0.2 * TOTAL(points1 points2) FILTER (WHERE modifier = 'modifier two') two,
0.7 * TOTAL(points1 points2) FILTER (WHERE modifier = 'modifier three') three
FROM tablename
GROUP BY parent;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/422603.html
標籤:
