使用sql选择查询条件数据

时间:2014-12-26 08:59:46

标签: sql

SELECT ka.* from Kisi.KisiAdres ka where ka.KisiID = '1192' OR ka.KisiID = '3'

我的上述查询给出了结果:

KisiAdresID     KisiID  AdresTurKod Adres               UlkeKod IlKod   IlceKod PostaKodu
    2114        3       ACI         3-Adress-ACI        TUR     01      163     01010
    2115        3       IKA         3-Adress-IKA-1      TUR     01      163     01010
    2117        3       IKA         3-Adress-IKA-2      TUR     01      163     01010
    3117        1192    IKA         1192-Adress-IKA     TUR     38      163     38380
    3118        1192    ACI         1192-Adress-ACI     TUR     38      163     38380
    3119        1192    DAI         1192-Adress-DAI     TUR     38      163     38380
    3120        1192    DAI         1192-Adress-DAI-1   TUR     38      163     38380

我有一张表,如上面的结果所示。

我想要的结果如下所示。

KisiAdresID     KisiID  AdresTurKod Adres     UlkeKod       IlKod   IlceKod PostaKodu
    2117        3       IKA 3-Adress-IKA-2    TUR           01      163     01010
    3120        1192    DAI 1192-Adress-DAI-1 TUR           38      163     38380

以上结果如下所示:

if exists (AdresTurKod=DAI), 
get row max(KisiAdresID) where AdresTurKod=DAI AND KisiID=1192)

not exist (AdresTurKod=DAI) and exists (AdresTurKod=IKA),
get row max(KisiAdresID) where AdresTurKod=IKA AND KisiID=1192)

not exist (AdresTurKod=DAI) and not exist (AdresTurKod=IKA) 
and exists (AdresTurKod=ACI), 
get row max(KisiAdresID) where AdresTurKod=ACI AND KisiID=1192)

or  

if exists (AdresTurKod=DAI), 
get row max(KisiAdresID) where AdresTurKod=DAI AND KisiID=3)

not exist (AdresTurKod=DAI) and exists (AdresTurKod=IKA),
get row max(KisiAdresID) where AdresTurKod=IKA AND KisiID=3)

not exist (AdresTurKod=DAI) and not exist (AdresTurKod=IKA) 
and exists (AdresTurKod=ACI), 
get row max(KisiAdresID) where AdresTurKod=ACI AND KisiID=3)

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您似乎想要将优先权应用于AdresTurKod

SELECT *
    ,case AdresTurKod
     when 'DAI' then 0
     when 'IKA' then 1
     when 'ACI' then 2
     End as preference 
FROM
     kisi.kisiAdres
 WHERE
     kisiID in (1192,3)
ORDER BY preference