我有这个简单的查询(TSQL) -
SELECT IdTour, Tour, TourOrder, IdContent
FROM View_ToursListContentId
WHERE (IdContent = 3) OR (IdContent = 4)
ORDER BY TourOrder DESC, Tour
结果如下
58 Air & Style Tour 2015/16 NULL 3
48 FIS Europa Cup 2015/16 NULL 3
46 FIS World Cup Tour 2015/16 NULL 3
131 KDC Grand Slam Regional Qualifiers 2016 NULL 3
59 Swatch Freeride World Tour 2016 NULL 3
77 World Rookie Tour 2015/16 NULL 3
57 World Snowboard Tour 2015/16 NULL 3
45 X Games 2016 NULL 3
45 X Games 2016 NULL 4
我需要做的是。如果在内部结果IdTour与IdContent = 3不要显示相同的IdTour与IdContent = 4.(显示IdTour与IdContent = 4,如果没有相同的IdTour与IdContent = 3 - 在我的情况下只显示一个IdTour 45与IdContent 3)
最简单,最快捷的方法是什么,我怎么能完成它?
Thanx很多
答案 0 :(得分:2)
一种方法涉及使用NOT EXISTS
:
SELECT IdTour, Tour, TourOrder, IdContent
FROM View_ToursListContentId t1
WHERE (IdContent = 3) OR
((IdContent = 4) AND NOT EXISTS (SELECT 1
FROM View_ToursListContentId t2
WHERE t1.IdTour = t2.IdTour AND
t2.IdContent = 3))
ORDER BY TourOrder DESC, Tour
如果存在具有相同NOT EXISTS
和IdContent = 4
的记录,则IdTour
运算符会过滤掉IdContent = 3
的记录。
答案 1 :(得分:0)
您可以使用窗口函数获取IdContent
可用的最低IdTour
:
SELECT IdTour,
Tour,
TourOrder,
IdContent,
MinIdContent = MIN(IdContent) OVER(PARTITION BY IdTour)
FROM View_ToursListContentId
WHERE IdContent IN (3, 4);
然后如果这是3然后你只选择3,如果它是4然后你只选择4,或者更简单,只选择匹配最小值的IdContent:
SELECT IdTour, Tour, TourOrder, IdContent
FROM ( SELECT IdTour,
Tour,
TourOrder,
IdContent,
MinIdContent = MIN(IdContent) OVER(PARTITION BY IdTour)
FROM View_ToursListContentId
WHERE IdContent IN (3, 4)
) AS t
WHERE IdContent = MinIdContent;
完整示例
WITH View_ToursListContentId AS
( SELECT IdTour, Tour, TourOrder, IdContent
FROM (VALUES
(58, 'Air & Style Tour 2015/16', NULL, 3),
(48, 'FIS Europa Cup 2015/16', NULL, 3),
(46, 'FIS World Cup Tour 2015/16', NULL, 3),
(131, 'KDC Grand Slam Regional Qualifiers 2016', NULL, 3),
(59, 'Swatch Freeride World Tour 2016', NULL, 3),
(77, 'World Rookie Tour 2015/16', NULL, 3),
(57, 'World Snowboard Tour 2015/16', NULL, 3),
(45, 'X Games 2016', NULL, 3),
(45, 'X Games 2016', NULL, 4)
) t (IdTour, Tour, TourOrder, IdContent)
)
SELECT IdTour, Tour, TourOrder, IdContent
FROM ( SELECT IdTour,
Tour,
TourOrder,
IdContent,
MinIdContent = MIN(IdContent) OVER(PARTITION BY IdTour)
FROM View_ToursListContentId
WHERE IdContent IN (3, 4)
) AS t
WHERE IdContent = MinIdContent;
答案 2 :(得分:0)
select * from (
select row_number() over (partition by IdTour, Tour, TourOrder order by IdContent) rownum,
IdTour, Tour, TourOrder, IdContent from View_ToursListContentId)src
where rownum=1
答案 3 :(得分:-1)
您应该在查询中使用group by IdContent
喜欢
SELECT IdTour, Tour, TourOrder, IdContent
FROM View_ToursListContentId
WHERE (IdContent = 3) OR (IdContent = 4)
group by IdContent
ORDER BY TourOrder DESC, Tour