请查看以下选择声明:
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'字段会成为一个问题,因为它可以是是或否我想只显示是,如果是可用,不是是和否所以它不会拉出重复的名字,比如'berry':
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
任何建议?
答案 0 :(得分: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, IsEated
的结果的查询来包装结果。使用MAX(IsWarm)
作为聚合函数,会为vlafors名称保留IsWarm
值DISTINCT
。我使用 CTE 编写此查询只是为了简单和可读性,但您可以将其编写为嵌套查询。