日期:2014-05-17  浏览次数:20485 次

sql重复数据问题
页面:


数据库:


数据库id自增,customername可以重名,customer,mobile 两个放在一起是唯一的。
现在想实现同一个顾客只显示一次,其余的购买信息通过点击后面的链接打开新窗口显示。


Sql="Select A.*,B.Flag From Customer A,(Select ID=Max(ID),Flag=Count(*) From Customer Where 1=1"

下面是asp语句,如果选则了时间进行汇总查询,sql语句会相应的在where 1=1 后增加条件
If Request("StartTime")<>"" Then
 Sql=Sql&" And Convert(DateTime,VisitTime)>=Convert(DateTime,'"&Request("StartTime")&"')"
End If

最后合成完整的sql语句进行查询
Sql=Sql& " Group By CustomerName,Mobile) B Where A.ID=B.ID Order By A.ID Desc"


当不输入任何条件的时候 sql 语句为:
Select A.*,B.Flag From Customer A,(Select ID=Max(ID),Flag=Count(*) From Customer where 1=1  Group By CustomerName,Mobile) B Where A.ID=B.ID Order By A.ID Desc
能实现要求。

但是如果加入了购买时间(VisitTime)进行查询 sql语句变为
Select A.*,B.Flag From Customer A,(Select ID=Max(ID),Flag=Count(*) From Customer where 1=1 And  Convert(DateTime,VisitTime)>=Convert(DateTime,Request("StartTime") Group By CustomerName,Mobile) B Where A.ID=B.ID Order By A.ID Desc

Request("StartTime")是所选择时间的值,
比如某客户  2014.1.1 2014.1.2购买过2次商品,不加时间条件,Flag=Count(*)=2 用asp 判断 flag>1 显示详细信息链接 正常。 
但是加入了时间限制 2014.1.1 这时候进行查询 Flag=Count(*)=1 flag不大于1 链接就不能正常显示出来了。

有没有sql语句 只要客户有2次及以上的购买记录 就加一个临时字段 里面放购买的次数 用于 asp来判断。
请教各位高人了。

------解决方案--------------------
----------------------------------------------------------------
-- Author  :DBA_Huangzj(發糞塗牆)
-- Date    :2014-01-23 11:00:10
-- Version:
--      Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64) 
-- Dec 28 2012 20:23:12 
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go 
create table [huang]([id] int,[name] varchar(4),[mobile] int,[Productname]&