我有一個查詢從臨時表中返回客戶數據。臨時表僅存儲客戶編號的名字和姓氏。它有資格參加一個節目的人的約320條記錄。在SQL語句中返回不正確的結果
create table #customers
(
customer_no int,
fname varchar(20),
lname varchar(55)
)
我需要從數據庫中做的是說給我從誰擁有姓氏和名字的組合,我們的整個數據庫大家(找到重複)。我們還需要提取地址,但我們不希望在搜索中使用客戶編號,因爲我們稍後需要編號,但現在我們希望比較僅限於名和姓。
select distinct a.customer_no,
a.fname,
a.mname,
a.lname,
b.street1,
b.street2,
b.city,
b.state,
b.postal_code
from T_CUSTOMER a
join T_ADDRESS b on a.customer_no = b.customer_no
where (
lname in (select lname from #customers) and
fname in (select fname from #customers)
)
order by a.lname, a.fname
因此該查詢返回的結果是記錄一個很好的一長串 - 然而,由於存在大量的重複組合(它帶回客戶號多次)。
例如:
customer_no fname mname lname street1 city
86224371 John NULL Cornid 11 Maplewood Dr. New Haven
86224371 John NULL Cornid 11 Maplewood Drive Hartford
86313525 John NULL Cornid 11 Maplewood Dr Hartford
86390546 John Seth Cornid 11 Maplewood dr. New Haven
所以數據是正確的。 唯一的問題是我想壓制第一行 - 我想說給我唯一的客戶號碼。我想我的輸出是:
customer_no fname mname lname street1 city
86224371 John NULL Cornid 11 Maplewood Dr. New Haven
86313525 John NULL Cornid 11 Maplewood Dr Hartford
86390546 John Seth Cornid 11 Maplewood dr. New Haven
我們必須提供基本信息來清理數據 - 我們只希望每個客戶編號都拉一次。
select distinct a.customer_no,
a.fname,
a.mname,
a.lname,
b.street1,
b.street2,
b.city,
b.state,
b.postal_code
from T_CUSTOMER a
join T_ADDRESS b on a.customer_no = b.customer_no
where (
lname in (select lname from #customers) and
fname in (select fname from #customers)
)
group by a.customer_no,
a.fname,
a.mname,
a.lname,
b.street1,
b.street2,
b.city,
b.state,
b.postal_code
having count(a.customer_no) > 1
order by a.lname, a.fname
我寫上述包括具有計數CUSTOMER_NO> 1,但它不工作,因爲它返回一個空數據集。
請指教。 謝謝。
對此處的更改抱歉......這不起作用。我有第一套記錄回來兩次。 86224371,86224371,86313525,86390546.是的地址是不同的,但我不在乎那些。我需要爲用戶提供唯一的客戶號碼。所以我需要它是86224371,86313525,86390546只。 – Elizabeth
好吧,它怎麼不起作用......你期望它沒有做什麼? – Hogan
我們有多個地址的記錄,並且它被返回並計數多次。但是,如果名稱不同,我只希望發生這種情況 - 並且客戶號碼不同。 – Elizabeth