我需要根据行值连接列名。以下是我的表格格式: -
表名= tbl_occupancy
所以从这张表中,如果它们的值 1 ,我需要在列下方连接: -
输出将采用以下格式: -
Working People/Owner Occupied/Students/Dss Referrals/Local Authority
when all of these columns value are one.
假设work_people& dss_referrals = 1然后我的输出将在下面: -
Working People/Dss Referrals
尝试一天。到目前为止还没有找到任何解
我需要在上面提到的单行中输出此输出。因为此查询将在报表模块中用作子查询。此输出将在xls工作表中显示为一列。
任何帮助PLZ。
答案 0 :(得分:2)
您可以在CASE
功能
CONCAT()
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
,但是它会有多个结果,但如果没有聚合函数则不能使用
答案 1 :(得分: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","")
);
答案 2 :(得分: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;
答案 3 :(得分:0)
您可以使用
“的concat-WS”
。它不会跳过空字符串。但是,它会在分隔符和参数之后跳过任何NULL值。
`mysql> SELECT CONCAT_WS(',','Test',NULL,'1');
output -> 'Test,1'`