如何在 SQL 中同时提取数据并将行转换为列

How to extract data & convert rows to columns at the same time in SQL

我找了一段时间了。虽然我看过一些例子,但我还没有找到符合我的情况的东西。

我试图从更大的 table 中提取数据,但我还想在此过程中转换行和列。我看到一些答案让我意识到我应该重新表述我的问题。我不知道 testscore 列中的值,这些只是示例。

ID  testscore
1     x
2     x
3     x
4     x

进入这个

testscore1 testscore2 testscore3 testscore4
x          x           x           x



  select 
        max(case ID when 1 then testscore else 0 end) as testscore1,
        max(case ID when 2 then testscore else 0 end) as testscore2,
        max(case ID when 3 then testscore else 0 end) as testscore3,
        max(case ID when 4 then testscore else 0 end) as testscore4
        from testtable

确实有效,但是它不能与同一 table 中的其他条目结合使用,但是谢谢

您可以使用表格

select (select testscore from scores where id = 1) as testscore1,
(select testscore from scores where id = 2) as testscore2,
(select testscore from scores where id = 3) as testscore3,
(select testscore from scores where id = 4) as testscore4

不太喜欢。但它有效。

我发布了 SQL server.Using PIVOT table

的答案
CREATE TABLE #Table(ID INT, testscore INT)

INSERT INTO #Table( ID ,testscore )
SELECT 1,96 UNION ALL
SELECT 2,94 UNION ALL
SELECT 3,97 UNION ALL
SELECT 4,91

SELECT *
FROM 
( 
 SELECT ID ,testscore
 FROM #Table
)A
PIVOT
(
  MAX(testscore) FOR ID IN ([1],[2],[3],[4])
) pvt

编辑:对于 Db,请尝试以下查询:

 SELECT MAX(CASE ID WHEN 1 THEN testscore ELSE 0 END) AS testscore1,
 MAX(CASE ID WHEN 2 THEN testscore ELSE 0 END) AS testscore2,
 MAX(CASE ID WHEN 3 THEN testscore ELSE 0 END) AS testscore3,
 MAX(CASE ID WHEN 4 THEN testscore ELSE 0 END) AS testscore4
 FROM #Table

试试这个

    select [1] as testscore1,[2] as testscore2,[3] as testscore3,[4] as testscore4
from 
(select  id,testscore from piv) p 
pivot
(max(testscore) for ID in ([1],[2],[3],[4])) as pvb

输出

testscore1  testscore2  testscore3  testscore4
96            94          97         91