0

ビューのクエリが 2 つあります。

最初のビュー:

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

2 番目のビュー:

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 句にも含まれていないため、選択リストでは無効です。

スコアに集計を使用せずに、最新の日付でスコアを取得することに固執しています。私は非常に多くの方法を試しましたが、最新の日付でスコアを取得する方法を理解できませんでした

  • 日付が異なる場合は最新のスコアを選択
  • 日付が同じ場合、最大スコアを選択

それは可能ですか?

上記の条件 でentity_idandを取得するにはどうすればよいですか?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 

この問題は解決しました。

4

1 に答える 1

0

最初: 2 番目のクエリで選択された列に小さなエラーがあります (t2.order2 の 3 倍)。

第二に、答えの一部:

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 では、操作 (max、first、sum など) なしで列を表示したい場合は、group by 句に列を入れる必要があります。

于 2012-12-16T10:35:47.133 に答える