CREATE TABLE `table`
(`source` varchar(20), `eventid` varchar(9), `system` varchar(10),`accountname` varchar(10))
;
INSERT INTO `table`
(`source`, `eventid`, `system` ,`accountname`)
VALUES
('uatapp', '528', 'bxw','jbb'),
('uatapp', '528', 'bxw','jbc'),
('nxapp', '530', 'gg','ff'),
('aaunswh20', '528', 'ccd','ff'),
('172.1.12.3', '528','vv','ff'),
('172.1.12.3', '528', 'vv', 'ff'),
('172.1.12.3', '528','vv','ff3')
;
如果我使用查询
SELECT SOURCE,accountname,SYSTEM, count(*)
FROM `table`
WHERE eventid = '528'
GROUP BY SOURCE,accountname
我得到了结果
SOURCE ACCOUNTNAME SYSTEM COUNT(*)
172.1.12.3 ff vv 2
172.1.12.3 ff3 vv 1
aaunswh20 ff ccd 1
uatapp jbb bxw 1
uatapp jbc bxw 1
我希望结果只显示
SOURCE ACCOUNTNAME SYSTEM COUNT(*)
172.1.12.3 ff vv 2
172.1.12.3 ff3 vv 1
uatapp jbb bxw 1
uatapp jbc bxw 1
(即)将源,帐户名分组为多行,而不是单行,如AAUNSWH20。
有人可以帮助制定查询吗?谢谢
答案 0 :(得分:1)
您可能拒绝的基本查询是正确显示来源和系统,但不按accountname
分组的基本查询:
SELECT source, system
FROM `table`
WHERE eventid = '528'
GROUP BY source, system
HAVING Count(DISTINCT accountname) >= 2;
问题在于,您无法查看使用了哪些帐户名称。这可以通过将此查询放入派生表中,并将连接返回到原始表来完成,如下所示:
SELECT DISTINCT
T.*
FROM
`table` T
INNER JOIN (
SELECT source, system
FROM `table`
WHERE eventid = '528'
GROUP BY source, system
HAVING Count(DISTINCT accountname) >= 2
) D ON T.source = D.source
AND T.system = D.system
WHERE
T.eventid = '528'
;
请参见此工作in a Sql Fiddle。
答案 1 :(得分:0)
也许你可以使用它:
SELECT SOURCE,accountname,SYSTEM, count(*)
FROM [table] a
WHERE eventid = '528'
and exists (select source, COUNT(*) from [table] b
where a.eventid = b.eventid
and a.source = b.source
group by source
having COUNT(*) > 1)
GROUP BY SOURCE,system,accountname
无论如何,table
是保留关键字,因此请在查询中使用[]
。