0

I have several tables in my database and want to select a couple columns from a couple tables, which is all fine. Now, there is a 3rd table, and this table has a column that has different text values in it, but the same few "text_values" for different users, for instance:

table3

row userid  text_value  value
1   user1   text1       value1
2   user1   text2       value2
3   user2   text1       value3
4   user3   text1       value4
...

Now, I want to take INFO1 and INFO2 from Table1, INFO3 and INFO4 from Table2, but then I want to take all the values from Table3 where text_value=text1 and make this a 5th column with INFO5, and then take values from Table3 where text_value=text2 and make this a 6th column with INFO 6.

I have the following query, which WORKS fine if I ONLY want the INFO5 column:

SELECT Table1.INFO1, Table1.userid , Table2.INFO2,
Table1.INFO3, Table2.INFO4,
Table3.value AS INFO5
FROM Table1 LEFT OUTER JOIN Table2 ON Table1.userid = Table2.userid 
LEFT OUTER JOIN Table3 ON Table1.userid = Table3.userid 
WHERE Table3.text_value = 'text1' 

However, I want to have another column created using the values from the same table3 VALUE column, but when TEXT_VALUE = 'text2' (this is true for 'text3', 'text4', as there are several texts to "filter" on).

When I change the query to the following, it doesn't work:

SELECT Table1.INFO1, Table1.userid , Table2.INFO2,
Table1.INFO3, Table2.INFO4,
Table3.value AS INFO5 WHERE Table3.text_value = 'text1' 
Table3.value AS INFO6 WHERE Table3.text_value = 'text2' 
FROM Table1 LEFT OUTER JOIN Table2 ON Table1.userid = Table2.userid 
LEFT OUTER JOIN Table3 ON Table1.userid = Table3.userid 

Any guidance will be appreciated.

4

3 回答 3

1

你需要一个CASE

SELECT  Table1.INFO1, 
        Table1.userid, 
        Table2.INFO2,
        Table1.INFO3, 
        Table2.INFO4,
        CASE WHEN Table3.text_value = 'text1' THEN Table3.value END AS INFO5 
        CASE WHEN Table3.text_value = 'text2' THEN Table3.value END AS INFO6 
FROM Table1 
LEFT OUTER JOIN Table2 
    ON Table1.userid = Table2.userid 
LEFT OUTER JOIN Table3 
    ON Table1.userid = Table3.userid 
于 2013-02-07T18:47:58.070 回答
0

您的 where 语句位于错误的位置。它应该在连接之后:

主要 SQL 语法应为:

SELECT Table1.INFO1, Table1.userid , Table2.INFO2,
Table1.INFO3, Table2.INFO4,
Table3.value AS INFO5 
Table3.value AS INFO6 
FROM Table1 LEFT OUTER JOIN Table2 ON Table1.userid = Table2.userid 
LEFT OUTER JOIN Table3 ON Table1.userid = Table3.userid 
WHERE Table3.text_value = 'text1' 
and Table3.text_value = 'text2' 
于 2013-02-07T18:47:10.817 回答
0

case 语句的替代方法是使用 Pivot 功能,如果您想在表 3 中添加更多 Info# 而不进行不必要的连接,它可以让您进行扩展。

http://sqlfiddle.com/#!3/789c8/1

于 2013-02-07T19:20:29.463 回答