2014-05-09 57 views
0

我有一個客戶表和一個地址表。基於加入表的計數和/或標誌的SQL選擇標誌

地址表有一個標誌,它是INVOICE,CORRESPONDENCE或DELIVERY。

客戶可以有0到多個地址記錄。

我希望能夠查詢表和生成基於地址數據的每個客戶的一個標誌 - 沒有地址記錄= NONE,1個或多個發票記錄= HASINVOICE,沒有發票,但1個或多個其他= HASOTHER

因此,下列數據:

+------------+---------+ 
| CustomerID | Name | 
+------------+---------+ 
|   1 | Peter | 
|   2 | Ray  | 
|   3 | Egon | 
|   4 | Winston | 
|   5 | Dana | 
+------------+---------+ 

+-----------+------------+----------------+ 
| AddressID | CustomerID | AddressType | 
+-----------+------------+----------------+ 
|   1 |   1 | INVOICE  | 
|   2 |   1 | DELIVERY  | 
|   3 |   2 | DELIVERY  | 
|   4 |   2 | CORRESPONDENCE | 
|   5 |   4 | INVOICE  | 
|   6 |   5 | CORRESPONDENCE | 
+-----------+------------+----------------+ 

我希望下面的輸出:

+------------+---------+-------------+ 
| CustomerID | Name | AddressFlag | 
+------------+---------+-------------+ 
|   1 | Peter | HASINVOICE | 
|   2 | Ray  | HASOTHER | 
|   3 | Egon | NONE  | 
|   4 | Winston | HASINVOICE | 
|   5 | Dana | HASOTHER | 
+------------+---------+-------------+ 

這是可能的,對於SQL 2000,使用單個闕ry和沒有遊標?

回答

3

我沒有2000實例方便(你真的應該升級,你4-5落後的版本),但我認爲這應該工作:

declare @Customers table (CustomerID int,Name varchar(10)) 
insert into @Customers (CustomerID,Name) 
select 1,'Peter' union all select 2,'Ray' union all 
select 3,'Egon' union all select 4,'Winston' union all 
select 5,'Dana' 

declare @Addresses table (AddressID int, CustomerID int, 
          AddressType varchar(30)) 
insert into @Addresses (AddressID,CustomerID,AddressType) 
select 1,1,'INVOICE' union all select 2,1,'DELIVERY' union all 
select 3,2,'DELIVERY' union all select 4,2,'CORRESPONDENCE' union all 
select 5,4,'INVOICE' union all select 6,5,'CORRESPONDENCE' 

select 
    c.CustomerID, 
    c.Name, 
    CASE MAX(CASE 
     WHEN a.AddressType = 'Invoice' THEN 2 
     WHEN a.AddressType IS NOT NULL THEN 1 
     END 
    ) WHEN 2 THEN 'HASINVOICE' 
    WHEN 1 THEN 'HASOTHER' 
    ELSE 'NONE' 
    END as AddressFlag 
from 
    @Customers c 
     left join 
    @Addresses a 
     on 
      c.CustomerID = a.CustomerID 
group by 
    c.CustomerID, 
    c.Name 

產地:

CustomerID Name  AddressFlag 
----------- ---------- ----------- 
5   Dana  HASOTHER 
3   Egon  NONE 
1   Peter  HASINVOICE 
2   Ray  HASOTHER 
4   Winston HASINVOICE 
+0

@podiluska - 是的。 2000年BOL仍然[可用](http://technet.microsoft.com/en-us/library/aa258839(v = sql.80).aspx)。即使它沒有,這只是構建一個演示該技術的自包含腳本。我可以想象OP會將它重新寫回原來的表格。 –

+0

今年我們正在升級!我的行業輪子慢慢轉動...... – Shevek