-1

我有一个如下所示的数据库:

Source   quoted    sold
google     1         0
google     0         0
google     1         1
google     1         0
google     1         1
direct     1         0
direct     0         0
direct     1         1
google     1         0

我想计算来自 google 的引用人数,以及同一行中来自 google 的购买人数,以及其他来源。所以上面的结果看起来像

Source  quotes   solds
google    5        2
direct    2        1
another   23       5   (not noted above, but there are countless more)

如何在 SQL 中获取这些信息?

4

5 回答 5

6

它看起来像一个简单SUMGROUP BY工作:

SELECT Source, SUM(quoted), SUM(Sold)
FROM MyTable
GROUP BY Source
于 2013-04-23T15:13:18.187 回答
4

如果这些列是列,我将提供不同的视角,而不是无数重复BIT。如果是,则当前查询将产生:

消息 8117,级别 16,状态 1,第 14 行
操作数数据类型位对于求和运算符无效。

要解决此问题,您可以使用以下结构之一:

DECLARE @t TABLE(Source VARCHAR(32), quoted BIT, sold BIT);

INSERT @t VALUES
('google',1,0),
('google',0,0),
('google',1,1),
('google',1,0),
('google',1,1),
('direct',1,0),
('direct',0,0),
('direct',1,1),
('google',1,0);

SELECT Source, 
    COUNT(NULLIF(quoted,0)), 
    COUNT(NULLIF(sold,  0))
 FROM @t
 GROUP BY Source;

SELECT Source, 
    SUM(CASE WHEN quoted = 1 THEN 1 ELSE 0 END),
    SUM(CASE WHEN sold   = 1 THEN 1 ELSE 0 END)
 FROM @t
 GROUP BY Source;

SELECT Source, 
    SUM(CONVERT(INT, quoted)),
    SUM(CONVERT(INT, sold))
 FROM @t
 GROUP BY Source;
于 2013-04-23T15:23:42.803 回答
2

我想这就是你要找的...

SELECT source, SUM(quoted), SUM(sold)
FROM your_table
GROUP BY source.
于 2013-04-23T15:14:17.120 回答
2

这需要基本GROUP BY语法,并且您的数据库已为此完美设置:

select source, sum(quoted) quoted, sum(sold) sold
from your_table
group by source;
于 2013-04-23T15:15:17.740 回答
-3
SELECT source, SUM(quoted = 1) AS quotes, SUM(solds = 1) AS solds
FROM yourtable
GROUP BY Source
于 2013-04-23T15:13:58.003 回答