1

小贩

VendorID  |   City
  1         LosAngels
  2         HongKong

供应商详情

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

主价值观

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

查询应返回每组 VendorID 的记录,如果其任何记录在 DetailCity 列中具有该值,则 City 应为 @GivenCityValue,否则 City 应为 Vendor 表的 City 列中的值

这可以通过 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 吗?

4

1 回答 1

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
于 2013-08-14T07:51:25.757 回答