在SQL Server中,我创建的视图显示表CONTACTS中的记录是否在不同的表TAGS中有某些标记。
这是我的疑问:
ID NAME A B C D
------------------------------------
1 BOB 1 0 0 1
1 Charlie 1 0 1 0
我希望结果如下:
ID NAME A B C D
------------------------------------
1 BOB 1 0 0 0
1 BOB 0 0 0 1
1 Charlie 1 0 0 0
1 Charlie 0 0 1 0
但我得到
import org.apache.commons.io.IOUtils
import java.nio.charset.StandardCharsets
def flowFile=session.get();
String attr=flowFile.getAttribute("count");
String fault=flowFile.getAttribute("error");
if(attr=="0"){
flowFile=session.putAttribute(flowFile,"empty","empty");
}
else if(fault!=" "){
log.error(fault.toString());
}
else {
flowFile=session.putAttribute(flowFile,"good","good");
}
session.transfer(flowFile,REL_SUCCESS);
一定是我忽略的东西,但我无法找到它。
答案 0 :(得分:3)
您只需使用GROUP BY
子句+ MAX
aggreate代替DISTINCT
SELECT contacts.ID, contacts.NAME
, MAX(IIF(tags.tag = 'A', 1, 0)) as A
, MAX(IIF(tags.tag = 'B', 1, 0)) as B
, MAX(IIF(tags.tag = 'C', 1, 0)) as C
, MAX(IIF(tags.tag = 'D', 1, 0)) as D
FROM contacts LEFT JOIN
TAGS ON contacts.ID = TAGS.CONTACT_ID
group by
contacts.ID, contacts.NAME
正如Gordon Linoff所说,使用标准SQL case when
与所有数据库(postgres,oracle,sql server ......)更兼容
IIF(tags.tag = 'A', 1, 0)
相当于
CASE WHEN tags.tag = 'A' THEN 1 ELSE 0 END
答案 1 :(得分:1)
SELECT contacts.ID, contacts.NAME
, MAX(IIF(tags.tag = 'A', 1, 0)) as A
, MAX(IIF(tags.tag = 'B', 1, 0)) as B
, MAX(IIF(tags.tag = 'C', 1, 0)) as C
, MAX(IIF(tags.tag = 'D', 1, 0) as D
FROM contacts LEFT JOIN
TAGS ON contacts.ID = TAGS.CONTACT_ID
GROUP BY contacts.ID, contacts.NAME
答案 2 :(得分:1)
使用group by
:
SELECT c.ID, c.NAME,
MAX(CASE WHEN t.tag = 'A' THEN 1 ELSE 0 END) as A,
MAX(CASE WHEN t.tag = 'B' THEN 1 ELSE 0 END) as B,
MAX(CASE WHEN t.tag = 'C' THEN 1 ELSE 0 END) as C,
MAX(CASE WHEN t.tag = 'D' THEN 1 ELSE 0 END) as D
FROM contacts c LEFT JOIN
TAGS t
ON c.ID = t.CONTACT_ID
GROUP BY c.ID, c.NAME;
注意更改查询:
SELECT DISTINCT
,因为您确实需要GROUP BY
。IIF()
更改为CASE
。我认为没有理由使用专为通过SQL标准函数向后兼容MS Access而设计的函数。