SQL Query根据条件选择一列的多个实例

时间:2015-08-13 04:04:14

标签: sql sql-server select join inner-join

我加入了3张桌子:

SELECT TABLE1.FIELD1
FROM TABLE1
JOIN TABLE2 ON TABLE1.ID = TABLE2.FK
JOIN TABLE3 ON TABLE2.ID = TABLE3.FK

我想根据某些条件选择几列TABLE2.FIELD1,例如TABLE2.FIELD1 WHERE TABLE2.CONDITIONITABLE2.FIELD1 WHERE TABLE3.ANOTHERCONDITION

所以最终的结果是这样的:

TABLE1.FIELD1 | TABLE2.FIELD1 BASE ON CON1 | TABLE2.FIELD1 BASED ON CON2

我不确定我是否足够清楚,如果需要,请要求进一步澄清。

示例报告:

Id |   Product | Income Quantity | Outcome Quantity

在此示例中,Quantity,在第二个表中仅在产品表上联合的一个字段中。它根据不同的条件在输出中呈现两次,例如,收入在header.flow == 1之内,而外向在header.flow == -1之内。

2 个答案:

答案 0 :(得分:1)

不确定,但似乎应该使用CASE声明

select 
case when <<cod1>> then
table1.field
when <<cod2>> then 
table2.field
end 
from your_table1
inner join your_table2 on <<condition>>

答案 1 :(得分:1)

像这样的东西

SELECT ID,
       CASE WHEN flow = 1 THEN Quantity ELSE NULL END as 'Income',
       CASE WHEN flow = -1 THEN Quantity ELSE NULL END as 'Outcome'
FROM Sample

只需在最后根据需要添加联接,并在CASE声明中更改条件

根据你的评论

  

我必须使用group by for flow和SUM(quantity)。我会为每种产品分两列。

您可以尝试这样做:

SELECT s1.ID,
    (SELECT SUM(Quantity) FROM SAMPLE s2 WHERE s2.ID = S1.ID AND S2.FLOW = 1) as 'Income',
    (SELECT SUM(Quantity) FROM SAMPLE s2 WHERE s2.ID = S1.ID AND S2.FLOW = -1) as 'Outgoing'
FROM Sample S1
GROUP BY ID

也可以通过

来实现
SELECT DISTINCT s1.ID,
    (SELECT SUM(Quantity) FROM SAMPLE s2 WHERE s2.ID = S1.ID AND S2.FLOW = 1) as 'Income',
    (SELECT SUM(Quantity) FROM SAMPLE s2 WHERE s2.ID = S1.ID AND S2.FLOW = -1) as 'Outgoing'
FROM Sample S1