我有一个如下表:
Where Product.Type = CInt(cmbProducts.SelectedValue)
如果标签为'A'或具有相同SomeNumber和最新日期的行,我希望从@T中选择数据:
例如SomeNumber 2,如果Tag ='A',则返回: (2,'A',NULL) 如果不存在带有标签“ A”的拖车,则返回: (2,'B','2018-11-09')
对于第二种情况,我正在考虑使用SomeDate DESC的SomeNumber顺序对row_number进行分区,然后获取rowNumber1。
但是,如何检查第一个条件为真,还是从同一列SomeNumber的第二列(SomeDate)获取最新的条件?
谢谢
答案 0 :(得分:1)
在与您查找的标签不匹配时选择标签的请求是不确定的:最新日期可能属于多个标签,因此您需要选择最小/最大(或任何聚合) ,或接受多个结果。例如。还有像这样的数据:
(2,'C','2018-11-09')。
此查询解决了您的问题,请注意,当与您查找的对象不匹配时,我使用了最小的Tag,并且还标记了修改查询的位置以不进行汇总并偶尔返回多行:
DECLARE @SomeNumber INT = 2, @Tag as VARCHAR(1) = 'A'
DECLARE @T TABLE
(
SomeNumber INT,
Tag VARCHAR(1),
SomeDate Datetime
)
INSERT INTO @T
(
SomeNumber,
Tag,
SomeDate
)
VALUES
(1, 'A', NULL),
(2, 'A', NULL),
(2, 'B', '2018-11-04'),
(2, 'B', '2018-11-08'),
(2, 'B', '2018-11-09'),
(2, 'C', '2018-11-09')
DECLARE @Result TABLE
(
SomeNumber INT,
Tag VARCHAR(1),
SomeDate Datetime
)
INSERT @Result
SELECT SomeNumber, Tag, MAX (SomeDate) as LatestDate
FROM @T
WHERE SomeNumber = @SomeNumber and Tag = @Tag
GROUP BY SomeNumber, Tag
-- SELECT * FROM @Result
IF @@ROWCOUNT = 0
BEGIN
INSERT @Result
SELECT
TagNotFound.SomeNumber
,MIN (T.Tag) as Tag -- use Tag only if you want all Tags for latest date
,TagNotFound.LatestDate
FROM (
SELECT SomeNumber, MAX (SomeDate) as LatestDate
FROM @T
WHERE SomeNumber = @SomeNumber
GROUP BY SomeNumber
) as TagNotFound
INNER JOIN @T as T
on T.SomeNumber = TagNotFound.SomeNumber and T.SomeDate = TagNotFound.LatestDate
GROUP BY TagNotFound.SomeNumber, TagNotFound.LatestDate -- comment this line out if you remove aggregate for Tag
END
SELECT * FROM @Result
我不想把整个东西放到一个SELECT中,以避免在匹配Tag时运行第二个更复杂的构造。
不同标签的结果:
对于“ A”,它给出2,“ A”,NULL
对于'B',它给出2,'B','2018-11-09'
对于'C',它给出2,'C','2018-11-09'
对于'D',它给出2,'B','2018-11-09'并在注释掉聚合时给出2行:
2,'B','2018-11-09'
2,'C','2018-11-09'
答案 1 :(得分:0)
尝试这样
int main(){
Bar * obj = new Foo();
Foo * obj2 = dynamic_cast<Foo*>(obj);
return 0;
}
答案 2 :(得分:0)
怎么样
SELECT SomeNumber,
Tag,
MAX(SomeDate) SomeDate
FROM @T
WHERE SomeNumber = 2 AND Tag =
(CASE
WHEN EXISTS(SELECT 1 FROM @T WHERE Tag = 'A' AND SomeNumber = 2) THEN 'A'
WHEN EXISTS(SELECT 1 FROM @T WHERE Tag = 'B' AND SomeNumber = 2) THEN 'B'
END)
GROUP BY SomeNumber, Tag;