SQL计数和不同的查询

时间:2016-02-26 21:46:04

标签: sql count distinct

我试图建立一个可以同时计算和区分的查询。这是原始数据

Raw Data

+--------+---------+
| IntID  | ErrorID |
+--------+---------+
| ins001 |    1    |
| ins001 |    1    |
| ins001 |    2    |
| ins002 |    3    |
| ins002 |    5    |
| ins002 |    5    |
| ins003 |    4    |
| ins003 |    1    |
| ins003 |    1    |
+--------+---------+

我想要完成的是每个不同的工具ID的每个错误ID的计数,如下所示:

What is expected

+--------+-------------+-------------+-------------+-------------+-------------+
| IntID  | ErrorID=001 | ErrorID=002 | ErrorID=003 | ErrorID=004 | ErrorID=005 |
+--------+-------------+-------------+-------------+-------------+-------------+
| ins001 |      2      |      1      |      0      |      0      |      0      |
| ins002 |      0      |      0      |      1      |      0      |      2      |
| ins003 |      2      |      0      |      0      |      1      |      0      |
+--------+-------------+-------------+-------------+-------------+-------------+

非常感谢任何建议或帮助。提前致谢

3 个答案:

答案 0 :(得分:2)

如果您提前知道一组有限的ErrorID,这应该可以使用。

    DECLARE @DisplayList    varchar(1000)
    DECLARE @SearchList     varchar(1000)
    DECLARE @sql            varchar(MAX)

    select @DisplayList = COALESCE(@DisplayList, '') + ',[' + cast(ErrorID as VARCHAR(100)) + '] as ' + ' [ErrorID=' + cast(ErrorID as VARCHAR(100)) + ']' from #YourErrorsTable
    select @SearchList = COALESCE(@SearchList, '') + ',[' + cast(ErrorID as VARCHAR(100)) + ']' from #YourErrorsTable

    set @sql = 'select IntID' + @DisplayList +'
        from
        (select IntID, ErrorID, 1 as cnt
            from #YourTable) as t
        pivot
        (
            count(cnt)
            for ErrorID in (' + RIGHT(@SearchList, LEN(@SearchList)-1) + ')
        ) as pvt'

    EXEC(@sql)

修改

根据您的要求,如果您有大量的错误,您可以动态构建查询。 Coalesce有助于为任意数量的错误构建字符串。 (RIGHT仅用于从字符串中删除第一个逗号)

{{1}}

答案 1 :(得分:1)

如果您使用的是MySql或PostgreSQL,则可以使用group by代替不同。

select InstrumentID, ErrorID, count (*)
from table
group by InstrumentID, ErrorID

答案 2 :(得分:0)

如果是少量错误ID,您可以执行以下操作。

<强> SQL Fiddle

SELECT 
    Instrumentid
  , SUM(CASE WHEN ErrorID = 1 THEN 1 ELSE 0 END) AS ErrorID_001
  , SUM(CASE WHEN ErrorID = 2 THEN 1 ELSE 0 END) AS ErrorID_002
  , SUM(CASE WHEN ErrorID = 3 THEN 1 ELSE 0 END) AS ErrorID_003
  , SUM(CASE WHEN ErrorID = 4 THEN 1 ELSE 0 END) AS ErrorID_004
  , SUM(CASE WHEN ErrorID = 5 THEN 1 ELSE 0 END) AS ErrorID_005
FROM YourTable
GROUP BY instrumentid