[在发布此问题之前,我已经完成了大量的问题。]
我有一个包含4个字段的表。它是 ClientId,ClientName,ClientAddress,ClientCity 。
现在,我有一个自动完成文本框控件,我需要在其中获取&显示客户名称。
问题是,在我们的数据库中,我们来自不同地址的同一城市的同一客户。
现在给我的要求是用户应该能够看到" ClientName"或" ClientName + ClientCity"或" ClientName + ClientCity + ClientAddress"使用户可以轻松选择客户端。
这意味着我需要在查询中添加一列,直到它使其唯一。
我确信必须有一些简单的解决方案,这是我过去2天没有得到的。
如下面的示例数据所示,如果我只显示" D"作为最终用户的客户名称,他会被困在哪个客户端" D"他必须选择。所以我们需要连接城市和地址以使其独一无二。
我期待输出如下。
答案 0 :(得分:1)
您可以使用COUNT() OVER()
:
;WITH CTE AS(
SELECT *,
ByName = COUNT(*) OVER(PARTITION BY ClientName),
ByCity = COUNT(*) OVER(PARTITION BY ClientName,ClientCity)
FROM Client
)
SELECT
CASE
WHEN ByName = 1 AND ByCity = 1 THEN ClientName
WHEN ByName > 1 AND ByCity = 1 THEN ClientName + ', ' + ClientCity
WHEN ByName > 1 AND ByCity > 1 THEN ClientName + ', ' + ClientCity + ', ' + ClientAddress
END
FROM CTE
ORDER BY ClientID
<强> RESULT 强>
Client
--------------------------------------------------------
A
B
C, New York
D, London, LSE Houghton Streen London WC2A 2AE
D, London, Hard Rock Cafe London 150 Old Park Lane
F
C, Paris
请参阅 SQL Fiddle 。
答案 1 :(得分:0)
如果您使用的是SQL Server,则可以使用&#34; +&#34;来尝试字符串连接。运营商如下
select
ClientName + ', ' + ClientCity + ', ' + ClientAddress as ClientData,
Concat(ClientName, ', ', ClientCity, ', ', ClientAddress) Client
from client
使用SQL CONCAT() funtion构建的第二个串联将适用于SQL Server 2012及更高版本
对于SELECT语句后面的条件数据可以提供帮助,
select
-- ClientName + ', ' + ClientCity + ', ' + ClientAddress as ClientData,
-- Concat(ClientName, ', ', ClientCity, ', ', ClientAddress) ClientDtata2,
client =
case when count(*) over (partition by ClientName) = 1 then ClientName
else
case when count(*) over (partition by ClientName, ClientCity) = 1 then CONCAT(ClientName, ', ' , ClientCity)
else Concat(ClientName, ', ', ClientCity, ', ', ClientAddress)
end
end
from client
答案 2 :(得分:0)
尝试这个,
Declare @t table (clientid int identity(1,1),clientname varchar(50),clientCITY varchar(50)
,clientaddress varchar(200))
insert into @t values ('A','PARIS','DFSDFSDF'), ('C','NEW YORK','DFSDFSDF')
,('C','PARIS','WEQWEQWE'),('D','LONDON','QWE342'),('D','LONDON','21DXCXZC')
;With CTE as
(select *,ROW_NUMBER()over(partition by clientname order by clientid)rn
,ROW_NUMBER()over(partition by clientname,ClientCity order by clientid)rn1
from @T A
)
--select * from cte
select clientname+','+ clientCITY
from cte A WHERE
EXISTS(SELECT CLIENTID FROM CTE WHERE clientname=A.clientname AND RN>1 AND RN1<=1)
UNION ALL
select clientname+','+ clientaddress
from cte A WHERE
EXISTS(SELECT CLIENTID FROM CTE WHERE clientname=A.clientname AND RN1>1)
UNION ALL
select clientname
from cte A WHERE not
EXISTS (SELECT CLIENTID FROM CTE WHERE clientname=A.clientname AND RN>1 )