SQL COUNT和SUM

时间:2015-05-14 08:41:04

标签: sql count sum base libreoffice

我有一张桌子 table done_by

Var_ID| Var_name| Q1_by  |Q2_by|Q3_by|Q4_by
1     |    abc  |   me   | me  |me   |you
2     |    cba  |   me   | me  |you  |you
3     |    abd  |   me   | you |you  |me

我想得到的结果是得到了所有的全部 我和你重视 我= 7 你= 5

已经完成了计数,但我无法得到的是所有的“我和我”。每列

4 个答案:

答案 0 :(得分:3)

你可以使用条件聚合,如:

SELECT SUM(CASE WHEN Q1_by = 'me' THEN 1 ELSE 0 END + 
           CASE WHEN Q2_by = 'me' THEN 1 ELSE 0 END +
           CASE WHEN Q3_by = 'me' THEN 1 ELSE 0 END +
           CASE WHEN Q4_by = 'me' THEN 1 ELSE 0 END) AS me ,
       SUM(CASE WHEN Q1_by = 'you' THEN 1 ELSE 0 END + 
           CASE WHEN Q2_by = 'you' THEN 1 ELSE 0 END +
           CASE WHEN Q3_by = 'you' THEN 1 ELSE 0 END +
           CASE WHEN Q4_by = 'you' THEN 1 ELSE 0 END) AS you
FROM TableName

答案 1 :(得分:0)

每季度使用个人计数并添加

SELECT (
(SELECT Count(Q1_by) FROM done_by WHERE Q1_by = 'me')+
(SELECT Count(Q2_by) FROM done_by WHERE Q2_by = 'me')+
(SELECT Count(Q3_by) FROM done_by WHERE Q3_by = 'me')+
(SELECT Count(Q4_by) FROM done_by WHERE Q4_by = 'me')) AS MeCount,
(
(SELECT Count(Q1_by) FROM done_by WHERE Q1_by = 'you')+
(SELECT Count(Q2_by) FROM done_by WHERE Q2_by = 'you')+
(SELECT Count(Q3_by) FROM done_by WHERE Q3_by = 'you')+
(SELECT Count(Q4_by) FROM done_by WHERE Q4_by = 'you')) AS YouCount
FROM done_by

IDEONE链接:https://ideone.com/ZAuS5O

答案 2 :(得分:0)

使用" Sum"的条件聚合;而不是" Count"如果你不知道不同的值,你可以使用动态sql来扩展它 -

--Dynamic SQL Extension to count sum of all distinct values
--Extract out distinct values in temporary table
SELECT DISTINCT by_val=val INTO #by_tbl FROM (SELECT  val=Q1_by
FROM #TableName
UNION ALL 
SELECT  val=Q2_by
FROM #TableName
UNION ALL 
SELECT val=Q3_by
FROM #TableName
UNION ALL 
SELECT val=Q4_by
FROM #TableName) A


--Create a SQL String 
DECLARE @sql NVARCHAR(max)

SELECT @sql = ISNULL(@sql+',', 'SELECT ') + '['+by_val+']=SUM(CASE WHEN Q1_by='''+by_val+''' THEN 1 ELSE 0 END 
                + CASE WHEN Q2_by='''+by_val+''' THEN 1 ELSE 0 END 
                + CASE WHEN Q3_by='''+by_val+''' THEN 1 ELSE 0 END 
                + CASE WHEN Q4_by='''+by_val+''' THEN 1 ELSE 0 END) '

FROM #by_tbl

SET @sql = @sql + ' FROM #TableName'

EXEC(@SQL)


DROP TABLE #TableName
DROP TABLE #by_tbl 

答案 3 :(得分:0)

DECLARE @byMe INT = 0;

SELECT @byMe = @byMe + COUNT(*) FROM dbo.tablName
WHERE Q1_by = 'me';

SELECT @byMe = @byMe + COUNT(*) FROM dbo.tablName
WHERE Q2_by = 'me';

SELECT @byMe = @byMe + COUNT(*) FROM dbo.tablName
WHERE Q3_by = 'me';

SELECT @byMe = @byMe + COUNT(*) FROM dbo.tablName
WHERE Q4_by = 'me';

SET @byMe = @byMe * 7;