CREATE TABLE IF NOT EXISTS sales (semester TEXT, amount REAL);
INSERT INTO sales VALUES('S1',100),('S1',100),('S1',100),('S1',100),('S1',100),('S1',100),('S2',100),('S2',100),('S2',100),('S2',100);
因此,您可以使用以下一体化查询:-
SELECT
(SELECT sum(amount) FROM sales) AS total,
(SELECT sum(amount) FROM sales WHERE semester = 'S1') AS s1total,
((SELECT sum(amount) FROM sales WHERE semester = 'S1') / (SELECT sum(amount) FROM sales)) * 100 AS s1prop,
(SELECT sum(amount) FROM sales WHERE semester = 'S2') AS s2total,
((SELECT sum(amount) FROM sales WHERE semester = 'S2') / (SELECT sum(amount) FROM sales)) * 100 AS s2prop
;
这将导致
即s1 prop和s2 prop预期结果(其他列可能有用)
另一种方法是使用CTE(公用表表达式)执行相同的操作:
WITH cte_total(total,s1total,s2total) AS (SELECT
(SELECT sum(amount) FROM sales),
(SELECT sum(amount) FROM sales WHERE semester = 'S1'),
(SELECT sum(amount) FROM sales WHERE semester = 'S2')
)
SELECT total, s1total, (s1total / total) * 100 AS s1prop, s2total, (s2total / total) * 100 AS s2prop FROM cte_total;
例如: 下面是一个示例,其中添加了第二个cte(作为第一个cte),模拟传递3个日期(而不是硬编码值?,可以编码,并通过参数绑定传递参数)。 由于sales表没有销售日期,因此对文字值进行了编码,这通常是具有销售日期的列,而不是WHERE '2023-01-01' /*<<<<< would be the column that holds the date */
硬编码日期已被有意使用,因此BETWEEN子句导致true。
如果日期列确实存在,则该学期的WHERE准则可以是该学期的相应日期之间的by。
示例:
WITH
dates AS (SELECT
'2023-01-01' /*<<<<< ? and can then be passed as bound parameter*/ AS startdate,
'2023-03-01' /*<<<<< ? and can then be passed as bound parameter*/ AS semester2_start,
'2023-05-30' /*<<<<< ? and can then be passed as bound parameter*/as enddate
),
cte_total(total,s1total,s2total) AS (SELECT
(SELECT sum(amount) FROM sales
WHERE '2023-01-01' /*<<<<< would be the column that holds the date */
BETWEEN (SELECT startdate FROM dates)
AND (SELECT enddate FROM dates)),
(SELECT sum(amount) FROM sales WHERE semester = 'S1'),
(SELECT sum(amount) FROM sales WHERE semester = 'S2')
)
SELECT total, s1total, (s1total / total) * 100 AS s1prop, s2total, (s2total / total) * 100 AS s2prop FROM cte_total;
1条答案
按热度按时间py49o6xq1#
答案是否定的但是:-
这可以在单个查询中完成。
考虑这个简单的演示与希望容易理解的所有在一个查询:-
首先是 sales 表:-
即学期和金额两栏
总共10行,因此总量为1000,6行为S1(数量为600),因此60%,4行为S2(数量为400),因此40%
创建和填充使用:-
因此,您可以使用以下一体化查询:-
这将导致
另一种方法是使用CTE(公用表表达式)执行相同的操作:
例如:
下面是一个示例,其中添加了第二个cte(作为第一个cte),模拟传递3个日期(而不是硬编码值
?
,可以编码,并通过参数绑定传递参数)。由于sales表没有销售日期,因此对文字值进行了编码,这通常是具有销售日期的列,而不是
WHERE '2023-01-01' /*<<<<< would be the column that holds the date */
示例: