日期:2014-05-16  浏览次数:20655 次

求一个SQL语句。在线等~~
如题,请会的朋友赐教。谢谢大家!

--
-- 表的结构 `test`
--

CREATE TABLE IF NOT EXISTS `test` (
  `id` int(5) NOT NULL,
  `mywaybill` varchar(20) NOT NULL,
  `mysite` varchar(20) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=gb2312;

--
-- 转存表中的数据 `test`
--

INSERT INTO `test` (`id`, `mywaybill`, `mysite`) VALUES
(1, '111', 'site1'),
(2, '222', 'site2'),
(3, '333', 'site2'),
(4, '111', 'site1'),
(5, '444', 'site1'),
(6, '222', 'site2');

###################################################################

上面这个表,我想实现的功能是:按mysite分组,显示出mywaybill字段至少重复出现过两条记录以上的。上面的这些数据,因为id为1和id为4的mywaybill字段值相同,所以这条是符合条件的,而id为5的只出现过一次,所以不符合。所以应该显示以下结果:

mysite count(*)
site1 1
site2 1


------解决方案--------------------
select mywaybill,count(*)
from test
group by mywaybill
having count(distinct mysite)>2
------解决方案--------------------
mysql> select mysite,1 as 'count(*)' from test group by mysite,mywaybill having count(0)>1;
+--------+----------+
| mysite | count(*) |
+--------+----------+
| site1 | 1 |
| site2 | 1 |
+--------+----------+
2 rows in set (0.00 sec)
------解决方案--------------------
select mysite,count(mywaybill)
from test
group by mysite
having count(mywaybill)>2