我有两个视图查询:
第一个观点:
SELECT
t1.entity_id, t1.entity_name,
t2.order1, t2.order2, t2.order3, t2.order4, t3.date, t2.score
FROM table1 t1
LEFT JOIN table2 t2 ON t1.entity_id = t2.entity_id
LEFT JOIN table3 t3 ON t2.code = t3.code
WHERE
t1.entity_id = 1
第二种观点:
SELECT
t1.entity_id, t1.entity_name,
t2.order1, t2.order2, t2.order3, t2.order4, max(t3.date) as 'date'
FROM table1 t1
LEFT JOIN table2 t2 ON t1.entity_id = t2.entity_id
LEFT JOIN table3 t3 ON t2.code = t3.code
WHERE
t1.entity_id = 1
GROUP BY
t1.entity_id, t1.entity_name, t2.order4, t2.order3, t2.order2, t2.order1
我遇到的问题是,当我尝试选择最长日期的最终得分时,会出现错误:
列'dbo.t2.score'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
我坚持使用最新日期得分,而不使用任何聚合得分。我已经尝试了很多方法,但我无法弄清楚得到最新日期的分数
如何获得具有此条件的分数(在检查order1至order4时,它是相同的):
有可能吗?
如何获得上述条件的entity_id
和score
?
view1的结果:
entity_id | entity_name | order1 | order2 | order3 | order4 | date | score
================================================================================
1 | entity 1 | aaa | rrr | eee | NULL | 2012-12-15 | 2
1 | entity 1 | aaa | rrr | eee | NULL | 2012-11-01 | 5.3
1 | entity 1 | bbb | sss | ttt | ggg | 2012-11-16 | 1.5
1 | entity 1 | ccc | sss | xxx | NULL | 2012-12-15 | 2.3
view2的结果:
entity_id | entity_name | order1 | order2 | order3 | order4 | date
========================================================================
1 | entity 1 | aaa | rrr | eee | NULL | 2012-12-15
1 | entity 1 | bbb | sss | ttt | ggg | 2012-11-16
1 | entity 1 | ccc | sss | xxx | NULL | 2012-12-15
我想要的结果:
entity_id | entity_name | order1 | order2 | order3 | order4 | date | score
================================================================================
1 | entity 1 | aaa | rrr | eee | NULL | 2012-12-15 | 2
1 | entity 1 | bbb | sss | ttt | ggg | 2012-11-16 | 1.5
1 | entity 1 | ccc | sss | xxx | NULL | 2012-12-15 | 2.3
我已经解决了这个问题。
答案 0 :(得分:0)
首先:在第二个查询中选择的列中有一个小错误(3次t2.order2)。
其次,答案的一部分:
SELECT
t1.entity_id, t1.entity_name, t2.order4, t2.order3, t2.order2, t2.order1, t2.score, max(t3.date) as 'date'
FROM table1 t1
LEFT JOIN table2 t2 ON t1.entity_id = t2.entity_id
LEFT JOIN table3 t3 ON t2.code = t3.code
WHERE
t1.entity_id = 1
GROUP BY
t1.entity_id, t1.entity_name, t2.order4, t2.order3, t2.order2, t2.order1, t2.score
如果我理解正确,您只想获得每个分数的结果,那么您只需将分数列添加到选择部分以及逐个分组。
请记住:在SQL-Server和Oracle中,如果要在没有操作的情况下显示列,则必须将列放在group by子句中(max,first,sum等)。