我有一个查询,我想要检索不同的child1
行,但是由共同父项关联的ORDERBY
行的属性排序。如果我执行以下操作,则会收到错误,因为DISTINCT
属性不在select
distinct c2.Id, c2.Foo, c2.Bar
from Child1 c1
join Parent p on c1.parentId = p.Id
join Child2 c2 on c2.parentId = p.Id
order by c1.Id
列表中:
c1.Id
但是,如果我将Child
添加到选择列表中,我将失去c1.Id
行的清晰度,因为#include <iostream>
template< typename ... BaseClasses >
class Meta
{
public:
virtual ~Meta() {}
template< typename T >
void call(const T& val)
{
callOnAllClasses<T, BaseClasses...>(val);
}
private:
template< typename T, typename HeadClass >
void callOnAllClasses(const T& val)
{
auto pObj = dynamic_cast<HeadClass*>(this);
if ( pObj )
pObj->HeadClass::doSomething(val);
}
template< typename T, typename HeadClass, typename ... TailClasses >
void callOnAllClasses(const T& val)
{
auto pObj = dynamic_cast<HeadClass*>(this);
if ( pObj )
pObj->HeadClass::doSomething(val);
callOnAllClasses<T, TailClasses...>(val);
}
};
class A
{
public:
void doSomething(int i)
{
std::cout << "A:" << i << std::endl;
}
};
class B
{
public:
void doSomething(int i)
{
std::cout << "B:" << i << std::endl;
}
};
class C : public B, public A, public Meta<C,B,A>
{
public:
void doSomething(int i)
{
std::cout << "C:" << i << std::endl;
}
};
int main()
{
C c;
c.call(5);
}
使它们完全不同。
如果我使用CTE或子查询首先进行排序,然后从中选择不同的行,则外部查询不保证它将保持内部/ cte查询的顺序。
有没有办法实现这个目标?
答案 0 :(得分:3)
我使用TOP(1) WITH TIES
在cte中创建不同的行,然后在查询中进行排序
WITH Data AS(
SELECT TOP(1) WITH TIES
g.id, g.foo, g.bar, p.createdDate
FROM Parent p
JOIN Child c on c.parentId = p.id
JOIN Grandchild g on g.childId = c.id
ORDER BY ROW_NUMBER() OVER(PARTITION BY g.id, g.foo, g.bar ORDER BY p.createdDate)
)
SELECT *
FROM Data
ORDER BY createdDate
TOP(1) WITH TIES
选择ROW_NUMBER()..
= 1的行。由于PARTITION BY ...
,每个分区(组)选择一行。它与GROUP BY
类似,但允许返回所有列
答案 1 :(得分:0)
使用内联表:
Select DISTINCT t.foo, t.bar From
(SELECT
c.foo, c.bar, p.createdDate
FROM Parent p
JOIN Child c on c.parentId = p.id
)t
ORDER BY t.createdDate