如果已在列中给出值,则从每个组中选择一条记录,否则为任何一条记录

时间:2013-08-14 07:44:40

标签: sql sql-server join aggregate-functions

供应商

VendorID  |   City
  1         LosAngels
  2         HongKong

VendorDetail

VendorDetailID |  DetailCity  | VendorID
      11          Cairo       1      
      12         MosCow       1
      13         Budapest     1
      14         NewDelhi     2
      15         Cairo        2

Mastervalues

  Text    | Value
LosAngels    LA
HongKong     HK
Cairo        CA
MosCow       Mo
Budapest     BU
NewDelhi     ND

如果其任何记录在DetailCity列中具有该值,则查询应返回每个VendorID组的记录,如果City的任何记录具有该值,则该城市应该是来自Cityor of Vendor表的值

这可以通过SubQuery和 Case When 表达式来实现。

SELECT VendorID,
   (SELECT Text FROM Mastervalues 
    Where Value IN(CASE WHEN (SELECT COUNT(*) 
                         FROM VendorDetail 
                         WHERE VendorID  = Vendor.VendorID AND DetailCity = @GivenCityValue)>0 
                    THEN  @GivenCityValue  
                    ELSE  Vendor.City END)) AS City 
   FROM Vendor

如果City的给定值为@GivenCityValue = 'Moscow',则所需结果为

VendorID | City
  1         MO
  2         HK

但我正在尝试加入自己。我们需要任何用户定义的聚合函数吗?  有没有办法使用join?

1 个答案:

答案 0 :(得分:0)

试试这个 -

SELECT VendorID
     , City
FROM Vendor
OUTER APPLY (
    SELECT City = [text]
    FROM Mastervalues
    WHERE EXISTS(
        SELECT COUNT(*)
        FROM VendorDetail
        WHERE VendorID = Vendor.VendorID
            AND DetailCity = @GivenCityValue
            AND value = DetailCity
    ) OR Vendor.City = value
) t