我有一个名为CorporateTree和Production的表,这些表的数据如下:
表:CorporateTree
DivisionName RegionName CommonName BU
Central Region 1 Raintree 101
Central Region 1 Glenwood 102
East Region 2 Balsa 201
East Region2 Warren 202
表:生产
ProdID BU ResidentName ResidentID Room
1 101 Smith, Jeff 234859 1002-A
2 202 Mill, Steve 125467 2002-B
3 101 Sisk, Paul 4383943 1009-C
4 101 Sims, Gary 384393 1010-A
5 202 Mason, Sam 32902 1012-A
我希望获得这样的输出:
Division Region Facility Business Unit ResidentCount Status
Central Region 1 Glenwood 102 0 Flag
Central Region 1 Raintree 101 3
East Region 2 Balsa 201 0 Flag
East Region 2 Warren 202 2
如果居民数量为零(0),则在状态
中输出“标志”的值我尝试了这个查询:
SELECT ct.DivisionName,ct.RegionName,ct.CommonName AS Facility,ct.BU AS [Business Unit],
(SELECT ROW_NUMBER() OVER (PARTITION BY p.BU ORDER BY p.BU DESC)) AS ResidentCount FROM
CorporateTree ct INNER JOIN Production p ON
p.Bu = ct.BU
但它似乎没有起作用?任何人都可以帮助我吗?
答案 0 :(得分:1)
您需要使用LEFT JOIN来计算生产表中没有行的任何业务单位。
SELECT ct.DivisionName, ct.RegionName, ct.CommonName AS Facility, ct.BU AS [Business Unit],
COUNT(p.BU) as ResidentCount,
CASE WHEN COUNT(p.BU) = 0 THEN 'Flag' ELSE '' END AS Status
FROM CorporateTree ct
LEFT JOIN Production p
ON p.BU = ct.BU
GROUP BY ct.DivisionName, ct.RegionName, ct.CommonName, ct.BU