【问题标题】:How to I set a column value from a COUNT subquery that joins with an outer query?如何从与外部查询连接的 COUNT 子查询中设置列值?
【发布时间】:2019-04-16 17:15:51
【问题描述】:

我有一个查询(最初是为 SQL Server 编写的),它有多个子查询作为计算计数的列。在 SQL Server 中,我可以有一个方程式来将一列设置为计数子查询,例如:

Pass = (select count(*) from report.sub_2018 p where p.ABST = a.ABST and p.RESULT = 'P' and p.STATUS_REASON = 'Pending' and p.MONTH_YEAR = a.MONTH_YEAR)

我正在尝试在 Vertica 中运行查询,但它不允许这种类型的“方程式”。所以我尝试做类似的事情

(select count(*) from report.sub_2018 p where p.ABST = a.ABST and p.RESULT = 'P' and p.STATUS_REASON = 'Pending' and p.MONTH_YEAR = a.MONTH_YEAR) as Pass

但由于它与外部查询相关,我收到错误Correlated subquery with aggregate function COUNT is not supported

这是我的查询:

select UserId = u.USER_ID,
Name = u.LNAME + ', ' + u.FNAME,
a.Month_Year,
(select count(*) from report.sub_2018 p where p.ABST = a.ABST and p.RESULT = 'P' and p.STATUS_REASON = 'Pending' and p.MONTH_YEAR = a.MONTH_YEAR) as Pass,
(select count(*) from report.sub_2018 p where p.ABST = a.ABST and p.RESULT = 'F' and p.STATUS_REASON = 'Pending' and p.MONTH_YEAR = a.MONTH_YEAR) as Fail,
(select count(*) from report.sub_2018 p where p.ABST = a.ABST and p.STATUS_REASON = 'Pending' and p.MONTH_YEAR = a.MONTH_YEAR) as Total
from report.sub_2018 a inner join pd_user_info u on a.ABST = u.USER_ID
where MONTH_YEAR like '2018-%' and u.USER_ID like 'MMN%'
group by u.LNAME, u.FNAME, a.MONTH_YEAR, a.ABST, u.USER_ID
order by u.LNAME, u.FNAME, a.MONTH_YEAR

我不太确定如何重新排列查询以使其与表 report.sub_2018 a 的外部查询一起使用

感谢任何帮助!

【问题讨论】:

    标签: sql vertica


    【解决方案1】:

    改为编写此查询

    select 
      u.USER_ID as UserId,
      u.LNAME || ', ' || u.FNAME as Name,
      a.Month_Year,
      count(case when a.RESULT = 'P' and a.STATUS_REASON = 'Pending' then 1 end) as Pass,
      count(case when a.RESULT = 'F' and a.STATUS_REASON = 'Pending' then 1 end) as Fail,
      count(case when                    a.STATUS_REASON = 'Pending' then 1 end) as Total
    from report.sub_2018 a 
    inner join pd_user_info u on a.ABST = u.USER_ID
    where MONTH_YEAR like '2018-%' and u.USER_ID like 'MMN%'
    group by u.LNAME, u.FNAME, a.MONTH_YEAR, a.ABST, u.USER_ID
    order by u.LNAME, u.FNAME, a.MONTH_YEAR
    

    这样,您只需访问sub_2018 表一次。 I have blogged about this technique recently.

    另请注意,在除 SQL Server 之外的大多数其他数据库中,使用此语法对列进行别名处理

    u.USER_ID as UserId
    

    ...不是这个 SQL Server 特定的:

    UserId = u.USER_ID
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-16
      • 1970-01-01
      相关资源
      最近更新 更多