计数和表中的值的总和

时间:2013-05-13 11:57:00

标签: sql ms-access

我在Access中有一个表,我想从中创建查询。我想计算第1列中值1发生的次数,第2列中值2发生的次数等。

ID  Col1    Col2    Col3  Col4
-------------------------------
172  1   2   4   3
172  3   2   4   1
173  2   3   5   4
173  2   1   3   4

输出(值出现次数):

             1   2   3   4   5   6   7   8
             ------------------------------
172  1st     1   0   1   0   0   0   0   0
172  2nd     0   2   0   0   0   0   0   0
172  3rd     0   0   0   2   0   0   0   0
172  4th     1   0   1   0   0   0   0   0
173  1st     0   2   0   0   0   0   0   0
173  2nd     1   0   1   0   0   0   0   0
173  3rd     0   0   1   1   1   0   0   0
173  4th     0   0   0   1   0   0   0   0
Total Count  3   2   4   3   1   0   0   0

2 个答案:

答案 0 :(得分:0)

由于您使用的是MS-Access,因此可以使用如下查询:

TRANSFORM Count([s].[ID]) AS Counts
SELECT [s].ID, [s].[tbl]
FROM (
     SELECT ID, '1st' AS tbl, [1st] AS Val FROM yourtable
     UNION ALL SELECT ID, '2st' AS tbl, [2nd] AS Val FROM yourtable
     UNION ALL SELECT ID, '3st' AS tbl, [3rd] AS Val FROM yourtable
     UNION ALL SELECT ID, '4st' AS tbl, [4th] AS Val FROM yourtable

)  AS [s]
GROUP BY [s].ID, [s].[tbl]
PIVOT [s].[Val];

如果您还想要总计,可以使用以下内容:

TRANSFORM Count([s].[ID]) AS Counts
SELECT [s].ID, [s].[tbl]
FROM (SELECT * FROM (
     SELECT ID, '1st' AS tbl, [1st] AS Val FROM yourtable
     UNION ALL SELECT ID, '2st' AS tbl, [2nd] AS Val FROM yourtable
     UNION ALL SELECT ID, '3st' AS tbl, [3rd] AS Val FROM yourtable
     UNION ALL SELECT ID, '4st' AS tbl, [4th] AS Val FROM yourtable)
  UNION ALL
   SELECT 999 AS ID, 'Total' AS tbl, Val FROM (
      SELECT ID, '1st' AS tbl, [1st] AS Val FROM yourtable
     UNION SELECT ID, '2st' AS tbl, [2nd] AS Val FROM yourtable
     UNION SELECT ID, '3st' AS tbl, [3rd] AS Val FROM yourtable
     UNION SELECT ID, '4st' AS tbl, [4th] AS Val FROM yourtable)
)  AS [s]
GROUP BY [s].ID, [s].[tbl]
PIVOT [s].[Val];

答案 1 :(得分:-1)

试试以下内容:

SELECT COUNT(DISTINCT 1st)
      , COUNT(DISTINCT 2nd)
      , COUNT(DISTINCT 3rd)
      , COUNT(DISTINCT 4th)
      , SUM(
            sum(COUNT(DISTINCT 1st))
           ,sum(COUNT(DISTINCT 2nd))
           ,sum(COUNT(DISTINCT 3rd))
           ,sum(COUNT(DISTINCT 4th))
        )  AS Total
  FROM tableName
 GROUP BY     1st, 2nd, 3rd, 4th

希望它有用。