SQL透视表与层级关联查询需求:基于两张表生成指定输出
Got it, let's work through this SQL problem step by step. First, let's recap the core requirements to make sure we're aligned:
- We need to combine data from
Table-1(which holds Critical/High values tied to Resources and Ranks 1-4) andTable-2(which tracks personnel, their issue levels, and associated Rank info via the RAM field) - The final output must include
Name, Issue, SLC, values, RESOURCEMISS - We can't use syntax like
[RESOURCEMISS]='Resource'
Step 1: Reshape Table-1 to Match Table-2's Structure
Table-1 has Rank1-Rank4 as columns, but we need to convert these into rows to join cleanly with Table-2's RAM field. For most SQL dialects (like SQL Server), we'll use UNPIVOT to do this:
SELECT Resource, RAM, values FROM Table-1 UNPIVOT ( values FOR RAM IN (Rank1, Rank2, Rank3, Rank4) ) AS UnpivotedTable1
This query turns each Rank column into a row pair: one with the RAM value (e.g., "Rank1") and its corresponding numerical value from Table-1.
Step 2: Join with Table-2 & Handle the RESOURCEMISS Field
Next, we'll left-join this reshaped data with Table-2 to pull in personnel details. For the RESOURCEMISS field, we'll use a CASE statement to flag missing Resource entries without using the forbidden syntax:
SELECT t2.Name, t2.Issue, t2.SLC, COALESCE(t1.values, 0) AS values, -- Replace 0 with NULL if you prefer to show blanks CASE WHEN t1.Resource IS NULL THEN 'Y' ELSE 'N' END AS RESOURCEMISS FROM Table-2 t2 LEFT JOIN ( SELECT Resource, RAM, values FROM Table-1 UNPIVOT ( values FOR RAM IN (Rank1, Rank2, Rank3, Rank4) ) AS UnpivotedTable1 ) t1 ON t2.RAM = t1.RAM AND t2.Issue IN ('Critical', 'High') -- Filter to match Table-1's Critical/High focus
Key Details to Note:
- Using
LEFT JOINensures we keep all records fromTable-2, even if there's no matching Resource inTable-1 - The
CASEstatement forRESOURCEMISSchecks directly for a NULL Resource value, avoiding the forbidden syntax COALESCEhandles NULL values from the join—adjust the default (0 here) to fit your reporting needs
Alternative for MySQL (No Native UNPIVOT Support)
If you're working with MySQL, which doesn't have built-in UNPIVOT, use UNION ALL to reshape Table-1 instead:
SELECT t2.Name, t2.Issue, t2.SLC, COALESCE(t1.values, 0) AS values, CASE WHEN t1.Resource IS NULL THEN 'Y' ELSE 'N' END AS RESOURCEMISS FROM Table-2 t2 LEFT JOIN ( SELECT Resource, 'Rank1' AS RAM, Rank1 AS values FROM Table-1 UNION ALL SELECT Resource, 'Rank2' AS RAM, Rank2 AS values FROM Table-1 UNION ALL SELECT Resource, 'Rank3' AS RAM, Rank3 AS values FROM Table-1 UNION ALL SELECT Resource, 'Rank4' AS RAM, Rank4 AS values FROM Table-1 ) t1 ON t2.RAM = t1.RAM AND t2.Issue IN ('Critical', 'High')
内容的提问来源于stack exchange,提问作者Srikanth

