SQL to transpose row pairs to columns in MS ACCESS database

戏子无情 提交于 2019-11-27 03:32:07

问题


I have an MS Access database that contains translated sentences in source-target pairs (a translation memory for fellow users of CAT tools). Somewhat annoyingly, source and target are not stored in separate columns, but in rows linked by ID, like this:

+---+----+--------------+
|id |lang|    text      |
+---+----+--------------+
  1   a     lang a text
  1   b     lang b text 
  2   a     more a text...
  2   b     more b text...
+---+----+--------------+

What SQL could I use to turn that into a table such as:

+---+--------------+--------------+
|id | lang A       | lang B       |
+---+--------------+--------------+
 1   lang a text    lang b text
 2   more a text... more b text...

Performance doesn't matter here, since would I only need to do this once in a while, and the db isn't huge (only a few thousand rows).


回答1:


A crosstab query should suit.

TRANSFORM First([Text]) AS LangText
SELECT ID, First([Text])
FROM Table 
GROUP BY ID
PIVOT lang

Further information: http://allenbrowne.com/ser-67.html




回答2:


You need a self-join:

SELECT
    t1.id, t1.text AS lang_a, t2.text AS lang_b
FROM
    lang_table AS t1
INNER JOIN
    lang_table AS t2
ON
    (t1.id = t2.id)
WHERE
    t1.lang = 'a'
AND
    t2.lang = 'b'



回答3:


select a.id, a.text as 'lang A', b.text as 'lang B'
from table a join table b on (a.id = b.id)
where a.lang = 'a' and b.lang = 'b';

where "table" is whatever table these are in.




回答4:


SELECT a.id,
MAX(CASE WHEN a.lang LIKE 'a' THEN a.text) AS Lang A,
MAX(CASE WHEN a.lang LIKE 'a' THEN a.text) AS Lang A
FROM table a
GROUP BY a.id


来源:https://stackoverflow.com/questions/736317/sql-to-transpose-row-pairs-to-columns-in-ms-access-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!