0

在 MS SQL 中,有没有一种方法可以根据第一列的值将条件列添加到如下的联合查询中?

基本上我试图将 bin 值添加为第四列,如果部件值类似于 ('%XX') 或让它显示 0,到目前为止,我只能添加另一列反映 MAX(part_bins.bin)如果代码不符合,列。

SELECT part_bins.part AS part,
       SUM(part_bins.free_stock) AS FREE_STOCK,
       MAX(PART_BINS.BIN) AS Bin
FROM part_bins
LEFT OUTER JOIN part ON part_bins.part = part.part
WHERE (part_bins.free_stock > 0)
GROUP BY part_bins.part
UNION
SELECT part.master_part AS part,
       SUM(part_bins.free_stock) AS FREE_STOCK,
       MAX(PART_BINS.BIN) AS Bin
FROM part_bins
LEFT OUTER JOIN part ON part_bins.part = part.part
WHERE (part_bins.free_stock > 0)
GROUP BY part.master_part
4

1 回答 1

1

您可以使用一条CASE语句,并且必须在两个查询中添加它才能添加第四列,例如;

--4th Column for both queries, if bin_value is a numeric type
case when part_value like '%XX' then bin_value 
       else 0 end as fourth_column

--4th Column for both queries, if bin_value is a string type
case when part_value like '%XX' then bin_value 
       else '0' end as fourth_column
于 2013-03-13T11:44:49.447 回答