SQL:根据 B 列中的布尔值更改 SELECT 查询以在 A 列上显示不同的值
Posted
技术标签:
【中文标题】SQL:根据 B 列中的布尔值更改 SELECT 查询以在 A 列上显示不同的值【英文标题】:SQL: Changing SELECT Query to Show Different Values on Column A based off Boolean in Column B 【发布时间】:2020-10-22 17:01:01 【问题描述】:我有一个产生此输出的 SQL 查询:
如果“CROSSDOMAIN”列的值为true?
,我将如何调整我的查询以使“SCORE”列的值增加 3 我想我会用处理这种情况的另一个查询,但我不确定该查询是什么。
我现有的查询如下(不是最漂亮的,但它有效):
SELECT HORSUM.TEAMNAME, HORSUM.EMAIL1, SUM(HORSUM.TOTALSUM) Score, COUNT(*) Count, TEAM.THEME, TEAM.FINALIST, TEAM.WINNER, TEAM.CROSSDOMAIN
FROM
(SELECT "JUDGEEMAIL", "TEAMNAME", "EMAIL1", "DEVOPSPRACTICES" + "BUSINESSIMPACT" +
"NEWSKILLS" + "EXECUTION"
+ "INNOVATION" + "CLARITY" as totalSum
FROM "DOMAINSCORES") AS HORSUM
INNER JOIN (SELECT "THEME", "TEAMNAME" as nameID, "FINALIST", "WINNER", "CROSSDOMAIN" FROM "TEAMS" WHERE "FINALIST" = True) AS TEAM ON HORSUM.TEAMNAME = TEAM.nameID
GROUP BY "TEAMNAME", EMAIL1, THEME, FINALIST, WINNER, CROSSDOMAIN
ORDER BY Score DESC;
编辑:按照 Michael 的建议,我已尝试过此查询,但出现语法错误。我还想补充一点,我正在使用 IBM 的 DB2,如果这有影响的话。
SELECT HORSUM.TEAMNAME
, HORSUM.EMAIL1
, case
when TEAM.CROSSDOMAIN = 'true'
then SUM(HORSUM.TOTALSUM) + 3
else SUM(HORSUM.TOTALSUM)
end as Score
, COUNT(*) Count
, TEAM.THEME
, TEAM.FINALIST
, TEAM.WINNER
, TEAM.CROSSDOMAIN
FROM
(SELECT HORSUM.TEAMNAME, HORSUM.EMAIL1, SUM(HORSUM.TOTALSUM) Score, COUNT(*) Count, TEAM.THEME, TEAM.FINALIST, TEAM.WINNER, TEAM.CROSSDOMAIN
FROM
(SELECT "JUDGEEMAIL", "TEAMNAME", "EMAIL1", "DEVOPSPRACTICES" + "BUSINESSIMPACT" +
"NEWSKILLS" + "EXECUTION"
+ "INNOVATION" + "CLARITY" as totalSum
FROM "DOMAINSCORES") AS HORSUM
INNER JOIN (SELECT "THEME", "TEAMNAME" as nameID, "FINALIST", "WINNER", "CROSSDOMAIN" FROM "TEAMS" WHERE "FINALIST" = True) AS TEAM ON HORSUM.TEAMNAME = TEAM.nameID
GROUP BY "TEAMNAME", EMAIL1, THEME, FINALIST, WINNER, CROSSDOMAIN)
ORDER BY Score DESC;
【问题讨论】:
【参考方案1】:试试这个作为外部 SELECT
SELECT HORSUM.TEAMNAME
, HORSUM.EMAIL1
, case
when TEAM.CROSSDOMAIN = 'true'
then SUM(HORSUM.TOTALSUM) + 3
else SUM(HORSUM.TOTALSUM)
end as Score
, COUNT(*) Count
, TEAM.THEME
, TEAM.FINALIST
, TEAM.WINNER
, TEAM.CROSSDOMAIN
...
【讨论】:
嗨,迈克尔,感谢您的快速回复。我正在尝试如下查询,但我收到错误“HORSUM.TEAMNAME”在使用它的上下文中无效。有什么想法吗? 查看我对上面原始问题的编辑,了解我正在尝试的内容。 您构建了一个额外的外部选择,这就是您遇到此问题的原因 - 替换原始查询的最外部选择(您的第一个 SELECT) 非常感谢迈克尔,你应该意识到这就是你的意思。很抱歉!以上是关于SQL:根据 B 列中的布尔值更改 SELECT 查询以在 A 列上显示不同的值的主要内容,如果未能解决你的问题,请参考以下文章
如何根据值 B 对 sql 中的列进行排序,其中字段中的值格式为 A-B-C。我