我有下表:
Sample
id PK
Test
id PK
name varchar
Section
id PK
name varchar
TestSection
id PK
test_id FK
section_id FK
SampleTestResult
id PK
sample_id FK
test_section_id FK
result
当我执行以下查询时:
SELECT DISTINCT
s.id as sample_id, ts.name as test, str.result
FROM sample s
JOIN sample_test_result str ON s.id=str.sample_id
JOIN test_section ts ON str.test_section_id=ts.id
JOIN section sec ON ts.section_id=sec.id
我得到一个像这样的表:
| sample_id | test | result |
--------------------------------------
| 1 | t1 | fail |
| 1 | t2 | pos |
| 2 | t1 | neg |
| 2 | t3 | rpt |
| 3 | t2 | pos |
| 3 | t4 | pos |
但是我最终要得到一个这样的表:
| sample_id | t1 | t2 | t3 | t4 |
--------------------------------------------
| 1 | fail | pos | NULL | NULL |
| 2 | neg | NULL | rpt | NULL |
| 3 | NULL | pos | NULL | pos |
如何在SQL中转置表格-这在查询中可能吗?还是必须是sql视图?
答案 0 :(得分:1)
对于MySQL,解决此问题的典型方法是使用条件聚合:
SELECT
s.id as sample_id,
MAX(CASE WHEN ts.name = 't1' THEN str.result END) as t1,
MAX(CASE WHEN ts.name = 't2' THEN str.result END) as t2,
MAX(CASE WHEN ts.name = 't3' THEN str.result END) as t3,
MAX(CASE WHEN ts.name = 't4' THEN str.result END) as t4
FROM
sample s
JOIN sample_test_result str ON s.id=str.sample_id
JOIN test_section ts ON str.test_section_id=ts.id
JOIN section sec ON ts.section_id=sec.id
GROUP BY s.id
答案 1 :(得分:1)
您需要条件聚合:
SELECT s.id as sample_id,
MAX(CASE WHEN ts.name = 't1' THEN str.result END) as t1,
. . .
FROM sample s JOIN
sample_test_result str
ON s.id=str.sample_id JOIN
test_section ts
ON str.test_section_id=ts.id
JOIN section sec ON ts.section_id=sec.id
GROUP BY s.id;