SQL:选择按相关子项的属性排序的不同子项

时间:2017-07-05 13:14:29

标签: sql sql-server subquery sql-order-by distinct

我有一个查询,我想要检索不同的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查询的顺序。

有没有办法实现这个目标?

2 个答案:

答案 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