2014-02-27 67 views
-1

我需要根据行值来连接列名称。下面是我的表格式: -concat列名取决于值

表名称= tbl_occupancy

enter image description here

从该表

所以,我需要Concat的下方列,如果他们的价值是: -

  1. working_people
  2. owner_occupied
  3. 名学生
  4. dss_referrals
  5. local_authority

输出会在下面的格式: -

Working People/Owner Occupied/Students/Dss Referrals/Local Authority 
when all of these columns value are one. 

假设如果working_people & dss_referrals = 1,那么我的输出将是如下所示: -

Working People/Dss Referrals 

尝试一天。直到现在还没有找到解决方案

我需要在上面提到的单行输出。因为此查询将在我的报告模块中作为子查询工作。此输出将显示为xls表格中的一列。

任何帮助PLZ。

+0

如果一个/多个它们的值是不是''1'',你怎么想的输出?你是否也可以发表带有其他栏目及其名称的列表预期产出? –

+0

@Ravinder检查我的编辑,如果可能删除否定的投票。我需要回答这个问题。 – ripa

+0

我不是那个贬低你的人。 –

回答

2

您可以使用CASECONCAT()函数内部

SELECT 
DISTINCT risk_reference, 
CONCAT(
CASE WHEN `working_people` = 1 THEN 'Working People /' ELSE '' END , 
CASE WHEN `owner_occupied` = 1 THEN 'Owner Occupied /' ELSE '' END , 
CASE WHEN `students` = 1 THEN 'Students /' ELSE '' END , 
CASE WHEN `dss_referrals` = 1 THEN 'Dss Referrals/' ELSE '' END , 
CASE WHEN `local_authority` = 1 THEN 'Local Authority' ELSE '' END 
) `concat_columns` 
FROM 
`table` 

编辑: 您可以使用DISTINCT得到不同的结果,但在你的表,你有多行所以会有多个结果虽然可以使用GROUP BY risk_reference但它不好用没有聚合功能

+0

或者你可以使用'CONCAT_WS'所以也就没有后面的斜线;)然后,你需要返回'NULL'如果该字段为0 – core1024

+0

@ core1024是'CONCAT_WS'可代替,但avisheks提供了使用'CONCAT_WS ' –

+0

你的sql给了我多行输出。我需要单排。 – ripa

0

你可以尝试像:

SELECT CONCAT_WS("/", 
IF(working_people=1,"working_people",""), 
IF(owner_occupied=1,"owner_occupied"), 
IF(students=1,"students",""), 
IF(dss_referrals=1,"dss_referrals",""), 
IF(local_authority=1,"local_authority","")) AS result 
FROM tbl_occupancy; 
0

可以使用

“CONCAT-WS”

。它不会跳过空字符串。但是,它在分隔符和参数之后跳过任何NULL值。

 `mysql> SELECT CONCAT_WS(',','Test',NULL,'1'); 
       output -> 'Test,1'` 
+0

plz正确地阅读问题。我知道如何以及在哪里使用concat_ws()。 – ripa

1

我使用下面的查询我的解决方案: -

select group_concat("/",col.column_name) as hazards from information_schema.columns 
    as col inner join db_name.`tbl_occupancy` as oc on col.table_schema="db_name" 
    and col.table_name = "tbl_occupancy" and col.column_name in (
      if(oc.working_people=1,"working_people",""), 
      if(oc.owner_occupied=1,"owner_occupied",""), 
      if(oc.students=1,"students",""), 
      if(oc.dss_referrals=1,"dss_referrals",""), 
      if(oc.local_authority=1,"local_authority","") 
    ); 
+0

而不是'group_concat(“/”,col.column_name)'使用'group_concat(col.column_name separator'/')'。您会在发布中按预期得到答案。 –

+0

@Ravinder好的。会做。感谢您的建议。 1个问题。我的答案质量好还是质量差? – ripa

+1

你为什么不直接在你的答案上运行'explain'和[*由@ MKhalidJunaid *回答](http://stackoverflow.com/a/22061706/767881)。这说明了很多。 –