SQL:如何使用带 case 表达式的外部别名进行子查询

问题描述 投票:0回答:1

如何创建一个使用 case 表达式的子查询的外列值的子查询?

SQL 示例:

SELECT
    name,
    average,
    crnt,
    goodFactor
FROM
(
 "Crispy Taco" AS name,
  ( SELECT avg(x)
    FROM (
     SELECT COUNT() x
     FROM tacos
     WHERE orderDate > DATEADD(DAY,  -1, GETDATE()))   <--- THE AVERAGE PRIOR TO TODAY
  ) AS average,
  COUNT(*) AS crnt,
  (
    SELECT
    CASE WHEN crnt < average    <---- PROBLEM HERE : Missing columns 'crnt' and 'average'
     THEN "not good"
     ELSE "pretty good"
    END
  ) AS goodFactor
)
from tacos

问题:

'

crnt
' 和 '
average
' 是 'goodFactor' 子查询的 '
missing columns
'

样本数据:(数据库条目)

+-------------+---------+---------+ | Name | Ordered | Date | +-------------+---------+---------+ | Crispy Taco | 1 | 8/29/24 | | Crispy Taco | 1 | 8/29/24 | | Crispy Taco | 1 | 8/29/24 | | Crispy Taco | 1 | 8/29/24 | | Crispy Taco | 1 | 8/29/24 | | Crispy Taco | 1 | 8/30/24 | | Crispy Taco | 1 | 8/30/24 | | Crispy Taco | 1 | 8/30/24 | | Crispy Taco | 1 | 8/30/24 | | Crispy Taco | 1 | 8/30/24 | | Crispy Taco | 12 | 8/31/24 | <---- ASSUME QUERY INVOKED THIS DAY PRODUCING THE TABLE BELOW +-------------+---------+---------+
预期结果:

如果“

crnt

”值大于计算的“
average
”
然后返回“
相当好”,否则返回“不好

预期结果

+-------------+---------------+---------+--------------------+ | Name | Daily Average | Current | GoodFactor | +-------------+---------------+---------+--------------------+ | Crispy Taco | 5 | 12 | pretty Good | +-------------+---------------+---------+--------------------+
    
sql select subquery case
1个回答
0
投票
这应该适用于所有标准 DBMS - 今天,即 2024 年 8 月 31 日,否则您 必须将所有地方的

CURRENT_DATE

 替换为 2024 年 8 月 31 日,并使用该样本数据:

WITH -- your input , don't use in final query indata(name,ordered,date) AS ( SELECT 'Crispy Taco', 1,DATE '08/29/24' UNION ALL SELECT 'Crispy Taco', 1,DATE '08/29/24' UNION ALL SELECT 'Crispy Taco', 1,DATE '08/29/24' UNION ALL SELECT 'Crispy Taco', 1,DATE '08/29/24' UNION ALL SELECT 'Crispy Taco', 1,DATE '08/29/24' UNION ALL SELECT 'Crispy Taco', 1,DATE '08/30/24' UNION ALL SELECT 'Crispy Taco', 1,DATE '08/30/24' UNION ALL SELECT 'Crispy Taco', 1,DATE '08/30/24' UNION ALL SELECT 'Crispy Taco', 1,DATE '08/30/24' UNION ALL SELECT 'Crispy Taco', 1,DATE '08/30/24' UNION ALL SELECT 'Crispy Taco',12,DATE '08/31/24' ) -- real query starts here, replace following comma with "WITH" , -- need a query grouping by day to get the daily sums -- before today daily AS ( SELECT name , date , SUM(ordered) AS per_day FROM indata WHERE date < CURRENT_DATE GROUP BY name , date ) , -- and one summing the current day current AS ( SELECT name , date , SUM(ordered) AS current FROM indata WHERE date=CURRENT_DATE GROUP BY name , date ) SELECT daily.name , AVG(per_day) AS "Daily Average" , MAX(current) AS current , CASE WHEN MAX(current) < AVG(per_day) THEN 'not good' ELSE 'pretty good' END AS good_factor FROM daily JOIN current ON daily.name = current.name GROUP BY daily.name;
名字每日平均当前好因素脆玉米饼512还不错
© www.soinside.com 2019 - 2024. All rights reserved.