是否可以在以下声明中为'a','b','test','123','blabla'
创建一些启示?
sum(case when col1 in ('a','b','test','123','blabla') then col2 end) as sum
我试图从letters_table
这样读取它:
sum(case when col1 in (select letter from letters_table) then col2 end) as sum
但它告诉我Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
以下对我不起作用:
DECLARE @letters varchar(10)
select @letters = letter FROM letters_table
sum(case when col1 in (@letters) then col2 end) as sum
因为当我打印@letters
时,只有最后一个'blabla'
答案 0 :(得分:3)
如果表格中有col1(文本列)和col2(数字列),请说myTable
和另一个表中的字母(文本列),比如letters_table
,那么你可以使用JOIN,如下所示:
SELECT
--mt.col1, Include for totals by col1
SUM(mt.col2)
FROM myTable mt
INNER JOIN letters_table lt
ON mt.col1 = lt.letter;
-- GROUP BY mt.col1 Include for totals by col1
-- ORDER BY mt.col1; Include for totals by col1
答案 1 :(得分:2)
使用子查询的第二个示例可能是最好的 - 您只需要在两个单独的阶段中执行子查询和聚合,如下所示:
select sum(x.col2) as sum
from (
select case
when col1 in (select letter from letters_table) then col2
else 0
end as col2
from YourTableName
) x
这应该按预期工作,并使解析器满意。
答案 2 :(得分:2)
...或者您可以使用公用表表达式,例如:
DECLARE @Test TABLE (col1 VARCHAR(1), col2 INT);
INSERT INTO @Test VALUES ('a', 1);
INSERT INTO @Test VALUES ('c', 20);
INSERT INTO @Test VALUES ('z', 3);
DECLARE @Letters TABLE (Letter VARCHAR(1));
INSERT INTO @Letters VALUES ('a');
INSERT INTO @Letters VALUES ('b');
INSERT INTO @Letters VALUES ('c');
WITH PreQuery AS (
SELECT
col1,
CASE WHEN l.Letter IS NULL THEN 0 ELSE 1 END AS GoodLetter,
col2
FROM
@Test t
LEFT JOIN @Letters l ON l.Letter = t.col1)
SELECT
SUM(CASE WHEN GoodLetter = 1 THEN col2 END)
FROM
PreQuery;
答案 3 :(得分:1)
solution posted by Richard应该可以解决问题,但不需要使用cte 你可以简单地使用下面的代码
select
isnull(sum(mt.col2),0)
from
myTbl mt
inner join lettersTbl lt
on mt.col1 = lt.letter
如果要包含结果中涉及的字母,可以使用变量。在这里查看your previous post是一个代码,其中包含您提供的相同示例数据
declare @yourTbl table (col1 char(1), col2 int);
insert into @yourTbl values ('a', 10)
,('b', 5)
,('c', 15)
,('d', 2)
,('a', 3)
,('b', 6)
,('c', 8)
,('d', 10);
declare @lettersTbl table (letter char(1));
-- insert your letters here
insert into @lettersTbl values ('a'),('b')
-- only needed if you want to display the letters involved too
declare @checkedLetters as varchar(50)
select @checkedLetters = concat(@checkedletters,lt.letter)
from
@letterstbl lt
select
@checkedletters
,isnull(sum(mt.col2),0)
from
@yourtbl mt
inner join @letterstbl lt
on mt.col1 = lt.letter