如何根据“案例陈述”中的值显示行

时间:2018-11-20 12:17:06

标签: sql sql-server tsql

我有一个查询,如下所示,并且仅当使用CASE的值是1时才要显示一行。请您告诉我我该怎么做

SELECT DISTINCT 
    a.AccountID, 
    a.ForeName, 
    a.Surname, 
    a.Gender, 
    CASE 
        WHEN B.Value = '1145' THEN '1' 
        WHEN B.Value = '1007' THEN '2' ELSE '0' 
    END AS Value, 
    b.Address,
     b.Town
FROM 
    Customer a
LEFT OUTER JOIN 
    AdditionalDetails b
ON 
    b.ID = a.AccountID

我得到的结果:

 AccountID  ForeName  Surname  Gender NoName  Address Town
  00012       Eric      Manse   Male    0      Porto   Porto
  00013       Peter     Mark    Male    0      Porto   Porto
  00014       Tom       Jerry   Male    0      Porto   Porto
  00014       Tom       Jerry   Male    1      Porto   Porto
  00015       Sarah     Parker  Female  0      Porto   Porto
  00015       Sarah     Parker  Female  1      Porto   Porto

如果CASE语句中有1,则它不应仅将值为1的行显示为0

3 个答案:

答案 0 :(得分:1)

我推测您想要MAX()MIN()

SELECT c.AccountID, c.ForeName, c.Surname, c.Gender, 
       MAX(CASE WHEN ad.Value = '1145' THEN '1'
                WHEN ad.Value = '1007' THEN '2'
                ELSE '0' 
           END),
      ad.Address, ad.Town
FROM Customer c LEFT OUTER JOIN
     AdditionalDetails ad
     ON c.ID = ad.ID
GROUP BY c.AccountID, c.ForeName, c.Surname, c.Gender, ad.Address, ad.Town;

编辑:

您似乎想确定优先级:

SELECT cad.*
FROM (SELECT c.AccountID, c.ForeName, c.Surname, c.Gender, 
             ad.Address, ad.Town,
             ROW_NUMBER() OVER (PARTITION BY c.ACCOUNTID
                                ORDER BY (CASE WHEN ad.Value = '1145' THEN 1
                                               WHEN ad.Value = '1007' THEN 2
                                               ELSE 0'
                                          END) DESC
                               ) as seqnum
      FROM Customer c LEFT OUTER JOIN
           AdditionalDetails ad
           ON c.ID = ad.ID
     ) cad
WHERE seqnum = 1;

答案 1 :(得分:1)

您已更改问题。您不是要查找不同的行,而是要对行进行排名并仅显示最佳匹配项。

根据您的确切要求,您可以使用RANKROW_NUMBER以及相应的ORDER BYPARTITION BY子句。

例如:

select c.*, ad.address, ad.town
from customer c
left join
(
  select
    address,
    town,
    customer_id,
    rank() over (partition by customer_id
                 order by case value when 1145 then 1 when 1007 then 2 else 0 end desc) as rnk
  from additionaldetails
) ad on ad.customer_id = c.id and d.rnk = 1;

答案 2 :(得分:0)

您可以尝试以下操作

 with cte as  (

        SELECT  a.AccountID, a.ForeName, a.Surname, a.Gender,
        b.Address, b.Town,         
        row_number() over(partition by a.AccountID
   order by 
     (CASE WHEN b.Value = '1145' THEN 1 WHEN b.Value = '1007' THEN 2 ELSE 0 
        END) desc) as val
        FROM Customer a
        LEFT OUTER JOIN AdditionalDetails b
        ON b.ID = a.AccountID    
       ) select * from cte where val=1