1

您好我需要帮助从基于特定行信息(蓝色和红色)的多列中获取数据,然后为每个行条件返回不同的列。

例子 :

来自 Table_Colours

ID |  Code Type  | Code
1  |  Blue       | Blue1XX
2  |  Red        | Red1XX
2  |  Blue       | Blue1XX
3  |  Red        | Red1XX
4  |  Blue       | Blue1XX
4  |  Red        | Red1XX
5  |  Blue       | Blue1XX

我需要返回

ID | Blue     | Red   
1  | Blue1XX  |        
2  | Blue1XX  | Red1XX
3  |          | Red1XX
4  | Blue1XX  | Red1XX
5  | Blue1XX  |      

蓝色总是返回 Blue1XX(6 个数字代码) 红色总是返回 Red1XX(5 个数字代码)

我需要使用特定的 ID 字符串进行搜索,例如:

AND ID IN (
'1',
'2',
'3',
'4',
)

任何帮助,将不胜感激。

4

3 回答 3

0

这假定您只有一个或没有与 ID 和特定 CodeType 匹配的内容。此外,它假设 MySQL。如果使用 SQL SERVER,删除LIMIT 1并放在TOP 1每个之后SELECT

SELECT DISTINCT ID, 
       (SELECT Code FROM MyTable AS T1 
        WHERE T1.ID=T0.ID AND T1.`Code Type`='Blue' LIMIT 1) AS BlueCode,
       (SELECT Code FROM MyTable AS T2 
        WHERE T2.ID=T0.ID AND T2.`Code Type`='Red' LIMIT 1) AS RedCode
FROM MyTable T0
WHERE T0.ID IN ('1','2','3')
ORDER BY T0.ID
于 2012-07-25T14:19:33.160 回答
0
WITH pair AS (
        WITH red AS (
                SELECT id,  zcode FROM table_colours WHERE code_type = 'Red'
                )
        , blue AS (
                SELECT id,  zcode FROM table_colours WHERE code_type = 'Blue'
                )
        SELECT COALESCE(b.id, r.id) AS id
                , b.zcode AS blue
                , r.zcode AS red
        FROM blue b
        FULL JOIN red r ON r.id = b.id
        )
SELECT * FROM pair
WHERE id IN (1,2,3,4)
        ;

结果:

 id |  blue   |  red   
----+---------+--------
  1 | Blue1XX | 
  2 | Blue1XX | Red1XX
  4 | Blue1XX | Red1XX
  3 |         | Red1XX
(4 rows)

注意:mysql-tag 是后来添加的。(mysql 不允许 CTE 的)

对 OP:你应该早先说过“它是 mysql”。在这种情况下,我不会费心创建基于 CTE 的答案。

于 2012-07-25T14:57:29.147 回答
-1

尝试这个:

select id, code as 'Blue', null as 'Red'
from table
where code_type like 'Blue'

union

select id, null as 'Blue', code as 'Red'
from table
where code_type like 'Red'
于 2012-07-25T14:16:32.120 回答