【问题标题】:SQL: Select within Select as subquerySQL:在选择中选择作为子查询
【发布时间】:2021-07-23 21:13:05
【问题描述】:

我有以下声明:

select 
    product_name as ShortestLength = (select top 1 product_name, len(fact_name) Value_Length 
                                      from table 
                                      order by Value_Length, fact_name ASC)

返回此输出:

shortestlength
PS

我想将此结果添加到另一个 select 语句:

select
    'Product' as Column_Name,
    avg(case when product is null then 1.000 else 0 end) * 100 as PctMissing,
    count(product) as TotalCount,
    count(distinct product) as UniqueCount
from 
    table

所以结果将是:

column_name pctmissing totalcount uniquecount shortestlength
Product 5.100 181186 15 PS

我应该在我的初始选择语句中添加什么?

【问题讨论】:

  • 您的第一个查询在语法上看起来不正确。我认为它应该会产生语法错误。请标记您正在使用的数据库。
  • 这里是PS 产品名称吗?

标签: sql sql-server select subquery sql-subselect


【解决方案1】:

您可以使用条件聚合:

select 'Product' as Column_Name,
        avg(case when t.product is null then 1.000 else 0 end)*100 as PctMissing,
        count(t.product) as TotalCount,
        count(distinct t.product) as UniqueCount,
        max(case when seqnum = 1 then product_name end) as shortest_length
from (select t.*,
             row_number() over (order by len(fact_name), fact_name) as seqnum
      from table t 
     ) t

这假定两个table 引用实际上是同一个表。

【讨论】:

    【解决方案2】:

    您可以将第一个查询用作子查询来代替 select 语句中的列:

    select
        'Product' as Column_Name,
        avg(case when product is null then 1.000 else 0 end)*100 as PctMissing,
        count(product) as TotalCount,
        count(distinct product) as UniqueCount,
    (select top 1 product_name from table order by Value_Length, fact_name ASC) as ShortestLength 
    from table
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-08
      • 1970-01-01
      • 2021-08-12
      • 2015-08-01
      相关资源
      最近更新 更多