日期:2014-05-19  浏览次数:20565 次

100分求一关于distinct的sql语句.
A
ID     IDA   NAME   COUNT
1         1       A           1
1         2       B           2

B
ID   IDA    
1     1
1     2   (如果只有一个主键id,那这条数据不可能存在,IDA是主键后,就可能存在了)
原来的sql:

select   sum(count)   as   Count,   ta.name,ta.id
from   A   ta,B   tb
where   a.id=b.id   and   a.ida=b.ida
group   by   ta.name,ta.id

B表原来只有一个主键ID,   后来加了一个主键IDA,
当进行关联查询的时候就可能出现四条结果.
这时候的结果就不对了,我还是想得到原来的结果,
这样的sql语句怎么写?应该用到distinct吧!




------解决方案--------------------
尽量别用distinct.
开始时觉得很不错.后来慢慢发现问题很严重.

比如
id aid datetime txt
1 2 2001-1-1 12:59:59 a
2 2 2001-1-1 12:59:59 a
调用这2条记录,如果你调了所有的值(*),再配合distinct,你会发现2条记录都会被调出来.
为什么?
因为在MSSQL数据的里的DATETIME是精确到毫秒甚至更低的.
2001-1-1 12:59:59 的时间你可以理解成2001-1-1 12:59:59:001和2001-1-1 12:59:59:999
解决方法?
1.你可以事先把2001-1-1 12:59:59简化成2001-1-1即单日期.
2.插入条件指定你所需要的结果,好像大概这样用吧?
sql= "select from 表名 t where not exists(select 1 from 表名 where 条件 and 条件 and id <t.id))
这条我在LEFT JOIN用成功过...不知道直接用行不行.
------解决方案--------------------
----创建测试数据
declare @ta table(ID int,IDA int, NAME varchar(10),[COUNT] int)
insert @ta
select 1, 1, 'A ', 1 union all
select 1, 2, 'B ', 2
declare @tb table(ID int,IDA int)
insert @tb
select 1, 1 union all
select 1, 2

----方法1(使用二个列作关联):
select sum([count]) as [Count], a.name,a.id
from @ta as a
inner join @tb as b
on a.id=b.id and a.ida=b.ida
group by a.name,a.id

----方法2(对B表使用子查询):
select sum([count]) as [Count], a.name,a.id
from @ta as a
inner join (select id from @tb group by id) as b
on a.id = b.id
group by a.name,a.id

/*结果
Count name id
----------- ---------- -----------
1 A 1
2 B 1
*/