如何在MS SQL中向联合查询添加条件列?

时间:2013-03-13 11:27:55

标签: sql sql-server

在MS SQL中,我是否可以根据第一列的值将条件列添加到联合查询中,如下所示?

基本上我试图将bin值添加为第四列,如果part值类似('%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

1 个答案:

答案 0 :(得分: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