选择具有不同 where 条件的同一列
Posted
技术标签:
【中文标题】选择具有不同 where 条件的同一列【英文标题】:Selecting same column with different where conditions 【发布时间】:2011-03-31 05:50:48 【问题描述】:此查询返回特定日期范围内特定销售人员的“已关闭”每日销售额的总和:
SELECT SUM(price) as closed_total FROM dbo.Sales WHERE salesperson_ID = @salesperson_ID AND date_ordered BETWEEN @start_date AND @end_date 和关闭 = 1 GROUP BY date_ordered输出如下:
每日总计 200 150 325 120 (等等)我想修改查询以返回一列用于已完成销售,一列用于所有销售(相同的查询,但没有“已关闭 = 1”条件),输出如下:
关闭总计 | all_total 200 | 275 150 | 150 325 | 500 120 | 280 (等等)我尝试使用 UNION 来组合单独的查询,如下所示:
SELECT SUM(price) as closed_total FROM dbo.Sales WHERE salesperson_ID = @salesperson_ID AND date_ordered BETWEEN @start_date AND @end_date 和关闭 = 1 GROUP BY date_ordered 联合所有 选择总和(价格)作为 all_total FROM dbo.Sales WHERE salesperson_ID = @salesperson_ID AND date_ordered BETWEEN @start_date AND @end_date GROUP BY date_ordered我认为这可能符合我的要求,但它将两个总和放入名为“closed_total”的单个列中。有什么想法吗?
【问题讨论】:
【参考方案1】:你可以试试这个
SELECT SUM(price) as total, SUM(CASE WHEN closed = 1 THEN price ELSE 0 END) as closed_total
FROM dbo.Sales
WHERE salesperson_ID = @salesperson_ID
AND date_ordered BETWEEN @start_date AND @end_date
GROUP BY date_ordered
【讨论】:
以上是关于选择具有不同 where 条件的同一列的主要内容,如果未能解决你的问题,请参考以下文章
Oracle PL/SQL - 根据条件对不同列进行选择、分组、排序、where-clause 的最佳方法?