我们可以在sqlite中使用at符号表示常量吗?

o75abkj4  于 2023-01-26  发布在  SQLite
关注(0)|答案(1)|浏览(164)

实际上可以在sqlite中使用@(at符号),以便能够在其他查询中将计算值用作常量。
我使用之前计算的变量(总计)来获得两个时间段内的另一个变量(比例)。
销售总额第一季度和第二季度销售额的比例。
我复制了第一个查询以获取常量,并将第一个查询复制到了第二个查询。

py49o6xq

py49o6xq1#

答案是否定的但是:-
这可以在单个查询中完成。
考虑这个简单的演示与希望容易理解的所有在一个查询:-
首先是 sales 表:-

即学期和金额两栏
总共10行,因此总量为1000,6行为S1(数量为600),因此60%,4行为S2(数量为400),因此40%
创建和填充使用:-

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(作为第一个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;

相关问题