SQL如何处理子类别

SQL如何处理子类别

新手在这里,所以希望这不是一个愚蠢的问题。我在SQL数据库中有一张实验室样本表。它包括Sample_ID,Test_Name,Subtest_Name和结果。我当前的简单SQL查询如下:

SELECT Sample, Test, Subtest, Result
    FROM table
WHERE Sample = 'list of sample #s'


这给出了以下结果:

SAMPLE  TEST    SUBTEST   RESULT
XX01    Test1   Test1Sub1   1
XX02    Test1   Test1Sub1   2
XX03    Test1   Test1Sub1   3
XX03    Test2   Test2Sub1   4
XX03    Test3   Test3Sub1   5
XX03    Test3   Test3Sub2   6
XX03    Test3   Test3Sub3   7
XX03    Test4   Test4Sub1   8
XX03    Test4   Test4Sub2   9
XX03    Test4   Test4Sub3   10


但是,我正在寻找要按唯一的Sample_ID列出的表,并将“子测试”列为列。我知道我要查找的子测试的名称,因此可以在查询中指定。例如,我希望上面的结果改为:

    Test1Sub1   Test2Sub1   Test3Sub1   Test3Sub2   Test3Sub3   Test4Sub1   Test4Sub2   Test4Sub3
XX01    1
XX02    2
XX03    3           4           5           6           7           8           9           10


有人可以为我提供SQL代码吗?我做了一些刻苦工作,但知识不足,不够具体,无法找到我想要的答案。谢谢!

最佳答案

CREATE TABLE #Test
(SAMPLE VARCHAR(100),  TEST VARCHAR(100),    SUBTEST VARCHAR(100),   RESULT INT)
INSERT INTO #TEST
VALUES
('XX01','Test1','Test1Sub1',   1   ),
('XX02','Test1','Test1Sub1',   2   ),
('XX03','Test1','Test1Sub1',   3   ),
('XX03','Test2','Test2Sub1',   4   ),
('XX03','Test3','Test3Sub1',   5   ),
('XX03','Test3','Test3Sub2',   6   ),
('XX03','Test3','Test3Sub3',   7   ),
('XX03','Test4','Test4Sub1',   8   ),
('XX03','Test4','Test4Sub2',   9   ),
('XX03','Test4','Test4Sub3',   10 )


SELECT *
FROM
 (
    SELECT SAMPLE,RESULT,SUBTEST
           FROM  #Test
) as s
PIVOT
(
    MAX(RESULT)
    FOR SUBTEST IN
(
Test1Sub1,
Test2Sub1,
Test3Sub1,
Test3Sub2,
Test3Sub3,
Test4Sub1,
Test4Sub2,
Test4Sub3
)
)AS pvt


mysql - SQL如何处理子类别-LMLPHP

关于mysql - SQL如何处理子类别,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41902373/

10-12 01:08