我正在尝试根据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语句中的存在来完成此操作。
答案 0 :(得分:2)
如果查询结果正确,那么您只需在该查询上+-----+--------+-------+-------+
| Age | PhysID | PedID | DocID |
+-----+--------+-------+-------+
| 28 | 111 | 123 | 111 |
| 26 | 111 | 123 | 111 |
| 3 | 111 | 123 | 123 |
+-----+--------+-------+-------+
:
group by