0

I have a table with 5 fields. Two of the fields will have duplicate values that match. I think I need to use one or two JOINS to get the data results I want.

Fields: Machine, Message, Date, Severity, ID

The two fields that will have duplicates are Machine and Message.

EXAMPLE DATA:

MACHINE  |  MESSAGE
--------------------
MACHINE1 |  ERROR1
MACHINE2 |  ERROR1
MACHINE3 |  ERROR1
MACHINE2 |  ERROR2
MACHINE2 |  ERROR2
MACHINE3 |  ERROR3
MACHINE1 |  ERROR3
MACHINE1 |  ERROR1

I need the results to be like this:

MACHINE1, 2 - ERROR1, 1 - ERROR3

MACHINE2, 1 - ERROR1, 2 - ERROR2

MACHINE3, 1 - ERROR1, 1 - ERROR3

I've been trying to search for the answer to this but haven't found the answer. I believe I will need JOIN or two with a possible GROUP BY.

4

2 回答 2

1
create table #machineErrors (Machine nvarchar(20), Error nvarchar(20))

insert into #machineErrors values ('Machine1','Error1')
insert into #machineErrors values ('Machine2','Error1')
insert into #machineErrors values ('Machine3','Error1')
insert into #machineErrors values ('Machine2','Error2')
insert into #machineErrors values ('Machine2','Error2')
insert into #machineErrors values ('Machine3','Error3')
insert into #machineErrors values ('Machine1','Error3')
insert into #machineErrors values ('Machine1','Error1')

select  Machine, COUNT(*), [Error]
from    #machineErrors
group by Machine, [Error]
order by Machine, [Error]
于 2012-04-19T20:27:22.713 回答
0

我不理解完整的问题,但似乎您正在寻找 SQL 中的旋转功能,以根据机器上的不同错误(1、2、3)聚合您的结果。

假设是 MSSQL ?? 因此,查询是基于您要汇总 3 个错误的假设。

SELECT Machine, [Error1], [Error2], [Error3]
FROM
    MessageTable
Pivot
(
  COUNT(Machine)
  FOR ErrorColumn 
  IN ([Error1], [Error2], [Error3])
)
于 2012-04-19T20:27:44.403 回答