子查询中的SQL分组

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

我正在尝试根据case语句对多个列进行分组。

我目前的代码如下:

SELECT
    p.SCODE AS PropNumber, p.SADDR1 AS propname,  
    (CASE 
        WHEN ut.scode LIKE '%m%' THEN 'Market'
        WHEN ut.scode LIKE '%t%' THEN 'LIHTC'
        WHEN ut.scode LIKE '%p%' THEN 'LIHTC/PHA'
        WHEN ut.scode LIKE '%s%' THEN 'S8'
        ELSE 'Other'
    END) AS detail_group, 
    COUNT(ut.scode) AS UnitCount, 
    (SELECT COUNT(*) AS MoveIns
     FROM tenant t1 
     JOIN unit u1 ON t1.hunit = u1.hmy
     JOIN property p1 ON p1.hmy = u1.hproperty
     JOIN unittype ut1 ON ut1.hmy = u1.HUNITTYPE
     WHERE t1.dtmovein >= getdate() - 14 
       AND p1.scode IN ('gsaff')
       AND p1.scode  = p.scode
       AND p1.saddr1 = p.saddr1
       AND ut1.scode = ut.scode) MoveIns 
FROM
    Property p 
JOIN
    unit u ON u.hproperty = p.hmy   
JOIN 
    unittype ut ON ut.hmy = u.hunittype  
WHERE 
    p.scode IN ('gsaff') 
    AND u.exclude = 0 
    AND ut.scode IN (SELECT ut22.scode FROM unittype ut22 GROUP BY ut22.scode)  
GROUP BY  
    (CASE 
        WHEN ut.scode LIKE '%m%' THEN 'Market'
        WHEN ut.scode LIKE '%t%' THEN 'LIHTC'
        WHEN ut.scode LIKE '%p%' THEN 'LIHTC/PHA'
        WHEN ut.scode LIKE '%s%' THEN 'S8'
        ELSE 'Other'
    END), p.scode, p.SADDR1, ut.scode

结果如下所示:

PropNumber  propname                detail_group    UnitCount   MoveIns
gsaff       Gardens at South Bay, LTD (gsaff)   Market             3    0
gsaff       Gardens at South Bay, LTD (gsaff)   Market             8    0
gsaff       Gardens at South Bay, LTD (gsaff)   Market             7    0
gsaff       Gardens at South Bay, LTD (gsaff)   Market             2    0
gsaff       Gardens at South Bay, LTD (gsaff)   LIHTC/PHA          3    0
gsaff       Gardens at South Bay, LTD (gsaff)   LIHTC/PHA         17    1
gsaff       Gardens at South Bay, LTD (gsaff)   LIHTC/PHA         23    3
gsaff       Gardens at South Bay, LTD (gsaff)   LIHTC/PHA         11    0
gsaff       Gardens at South Bay, LTD (gsaff)   LIHTC/PHA          2    0
gsaff       Gardens at South Bay, LTD (gsaff)   LIHTC/PHA         10    0
gsaff       Gardens at South Bay, LTD (gsaff)   LIHTC/PHA         11    0
gsaff       Gardens at South Bay, LTD (gsaff)   LIHTC/PHA          2    0 

我想要的是将所有Market和lihtc / pha汇总到一个组中,结果如下:

  PropNumber   propname                detail_group    UnitCount   MoveIns
gsaff       Gardens at South Bay, LTD (gsaff)   Market            20    0
gsaff       Gardens at South Bay, LTD (gsaff)   LIHTC/PHA         79    4 

单元类型中的实际数据是m1,m2,m3和tc1,tc2等,因此当在ut1.scode = ut.scode上的子查询中链接回来时,这是多行的原因。我也意识到我只能在子查询中返回一个值,所以我猜我需要以某种方式使用where语句中的存在来实现这一点。

sql
1个回答
2
投票

如果查询结果正确,那么您在该查询中只需要group by

select 
  t.PropNumber, t.propname, t.detail_group, 
  sum(t.UnitCount) UnitCount, sum(t.MoveIns) MoveIns
from (
  <your query>
) t
group by 
  t.PropNumber, t.propname, t.detail_group
© www.soinside.com 2019 - 2024. All rights reserved.