SQL 将行转换为列

SQL Convert rows into columns

我有以下输出:

Username shortname data
test1 firm Google
test1 type IT
test1 agreed 1
test2 firm Facebook
test2 type IT
test2 agreed 1
test2 newsletter 1

我想创建另一个专栏,内容如下:如果用户名的简称为“newsletter”,并且“newsletter”的数据为“1”,则为“yes”,如果用户名没有 newsletter,则为“no”。 =14=]

所以我想得到以下输出:

Username yes/no
test1 no
test2 yes

我做了以下代码:

SELECT distinct(if(shortname = 'newsletter' and data = 1, 'Yes', 'No')) as 'Yes/no', username
FROM prefix_user as u
JOIN prefix_user_info_data as uid ON uid.userid = u.id
JOIN prefix_user_info_field as uif ON uid.fieldid = uif.id

但这会在每一行中写出是或否

这是在 Oracle 上吗?实际上,即使不是,您也可以在下面的查询中采纳这个想法。

select case 
        when shortname = 'newsletter' and data = '1'
         then 'YES' 
        else 'NO' 
       end as yes_no 
  from prefix_user as u 
  JOIN prefix_user_info_data as uid 
    ON uid.userid = u.id 
  JOIN prefix_user_info_field as uif 
    ON uid.fieldid = uif.id

根据您添加的标签,我将其视为 MySQL。在你的 IF 条件中,在 shortname='newsletter' 的情况下,你将不得不添加一个嵌套的 IF 条件来检查数据值是否等于 1.

查询将类似于以下内容,用于检查将根据 IF 条件选择所有用户而不是 DISTINCT:

SELECT
    IF( shortname = 'newsletter',
        IF (
            data= 1,
            'yes',
        'No')
    , 'No') AS 'Yes/no',
    username,shortname, data
FROM
    test1 AS u   //Relace your table name here
//add joins with other tables that you requires.

您可以使用条件聚合作为

SELECT username,
       MAX(CASE
           WHEN shortname = 'newsletter' AND data = 1 THEN
            'Yes'
           ELSE
            'No'
           END) AS "yes/no"
  FROM prefix_user as u
  JOIN prefix_user_info_data as uid
    ON uid.userid = u.id
  JOIN prefix_user_info_field as uif
    ON uid.fieldid = uif.id
 GROUP BY username

考虑到单词的字母顺序 Yes 晚于 No