在新列上使用条件对列值求和

时间:2017-07-19 06:32:14

标签: sql ms-access select

假设我有下表:

Letter  Item1  Item2
'a'     2      3
'b'     3      5
'c'     6      7

如果单词包含某些字母,我如何编写一个返回我传递的单词的项目总和的查询?例如:

Word  Sum
'ab'  13
'abc' 26
'bc'  21

编辑:我需要在查询中传递几个单词。

2 个答案:

答案 0 :(得分:0)

考虑一下:

SELECT [enter word] AS Word, Sum(IIf(InStr([enter word],[Letter])>0,[Item1]+[Item2],0)) AS LtrSum FROM Table1 GROUP BY [enter word];

SELECT DISTINCT [enter word1] AS W1, Sum(IIf(InStr([enter word1],[Letter])>0,[Item1]+[Item2],0)) AS C1, [enter word2] AS W2, Sum(IIf(InStr([enter word2],[Letter])>0,[Item1]+[Item2],0)) AS C2, [enter word3] AS W3, Sum(IIf(InStr([enter word3],[Letter])>0,[Item1]+[Item2],0)) AS C3 FROM Table1 GROUP BY [enter word1], [enter word2], [enter word3];

SELECT DISTINCT [enter word1] AS W1, DSum("Item1","Table1","InStr('" & [enter word1] & "', [Letter])>0")+DSum("Item2","Table1","InStr('" & [enter word1] & "', [Letter])>0") AS C1, [enter word2] AS W2, DSum("Item1","Table1","InStr('" & [enter word2] & "', [Letter])>0")+DSum("Item2","Table1","InStr('" & [enter word2] & "', [Letter])>0") AS C2, [enter word3] AS W3, DSum("Item1","Table1","InStr('" & [enter word3] & "', [Letter])>0")+DSum("Item2","Table1","InStr('" & [enter word3] & "', [Letter])>0") AS C3 FROM Table1;

SELECT Table2.Word, Sum(IIf(InStr([Word],[Letter])>0,[Item1]+[Item2],0)) AS LtrSum FROM Table2, Table1 GROUP BY Table2.Word;

答案 1 :(得分:0)

您只需使用CHARINDEX

即可
SELECT SUM(Item1) + SUM(Item2)
FROM TABLE_NAME WHERE CHARINDEX(Letter, ENTER_WORD) > 0