3

请查看下面的选择声明:

  SELECT 
    fc.flavorid,
    fc.flavorname,
    CASE 
      WHEN sa.flavorid IS NULL THEN 'No'
      ELSE 'Yes' END ) IsEaten
    CASE 
      WHEN t.tempid IS NULL THEN 'No' 
      ELSE 'Yes' END ) IsWarm

  FROM [poptart] p

    LEFT JOIN [diet] d ON d.Active = 1
    LEFT JOIN [toaster] ts ON p.poptartid = ts.poptartid AND d.dietname = ts.dietname
    LEFT JOIN [flavor] fl ON fl.poptartid = ts.poptartid
    LEFT JOIN [flavorcolor] fc ON fc.flavorid = fl.flavorid

    LEFT OUTER JOIN [stomach] sa ON sa.flavorid = fc.flavorid

    LEFT JOIN [poptart] p2 ON ts.poptartid = p2.poptartid
    LEFT JOIN [temp] t ON t.tempid = p2.tempid AND t.Active = 1

  GROUP BY fc.flavorid,fc.flavorname,sa.flavorid,t.tempid
  ORDER By fc.flavorname

正如您在下面看到的,这为 'berry' 的每个 'IsWarm' 值返回一个。我只想在此列表中返回不同的风味名称,但“IsWarm”字段已成为问题,因为它可以是“是”或“否”,我只想在“是”可用时显示“是”,而不是“是”和“否”,因此不会提取重复的风味名称,例如“浆果”:

    flavorid  |  flavorname  |  IsEaten  |  IsWarm
      123     |    berry     |    No     |   Yes
      123     |    berry     |    No     |   No
      234     |    fudge     |    Yes    |   No
      235     |    honey     |    No     |   No

我如何让这个语句只返回这个..?

  flavorid  |  flavorname  |  IsEaten  |  IsWarm
    123     |    berry     |    No     |   Yes
    234     |    fudge     |    Yes    |   No
    235     |    honey     |    No     |   No

有什么建议么?

4

1 回答 1

3

试试这个:

;WITH FlavorsList
AS
( 
    //Your query here
    SELECT 
      fc.flavorid,
      fc.flavorname,
    CASE 
      WHEN sa.flavorid IS NULL THEN 'No'
      ELSE 'Yes' END ) IsEaten
    CASE 
      WHEN t.tempid IS NULL THEN 'No' 
      ELSE 'Yes' END ) IsWarm

  FROM [poptart] p

    LEFT JOIN [diet] d ON d.Active = 1
    LEFT JOIN [toaster] ts ON p.poptartid = ts.poptartid 
                           AND d.dietname = ts.dietname
    LEFT JOIN [flavor] fl ON fl.poptartid = ts.poptartid
    LEFT JOIN [flavorcolor] fc ON fc.flavorid = fl.flavorid

    LEFT OUTER JOIN [stomach] sa ON sa.flavorid = fc.flavorid

    LEFT JOIN [poptart] p2 ON ts.poptartid = p2.poptartid
    LEFT JOIN [temp] t ON t.tempid = p2.tempid AND t.Active = 1

  GROUP BY fc.flavorid,fc.flavorname,sa.flavorid,t.tempid
)
SELECT fl.flavorid, fl.flavorname, fl.IsEaten, Max(fl.IsWarm)
FROM FlavorsList fl
GROUP BY fl.flavorid, fl.flavorname, fl.IsEaten
ORDER BY fl.flavorname

我在这里所做的是用一个查询包装你的结果,该查询将GROUP来自你的第一个查询的结果BY flavorid, flavorname, IsEatedMAX(IsWarm)用作聚合函数,将保留vlafors名称的IsWarmDISTINCT我使用CTE编写此查询只是为了简单和易读,但您可以将其编写为嵌套查询。

于 2012-04-21T05:44:22.490 回答