我创建了一个包含两个CASE列的视图。 在最后一列中,我需要得到这些案例字段的总和。 代码
CREATE VIEW full_return_data
AS
SELECT
return.ID_issuance,
CASE WHEN DATEDIFF(d, date_of_return, fact_date_of_return) <= 0 THEN 0
WHEN (fact_date_of_return is NULL) THEN book_local.price
ELSE DATEDIFF(d,date_of_return, fact_date_of_return) * 30
END AS fine1,
CASE WHEN [return].ID_condition > book_exemplar_condition.ID_condition AND [return].ID_condition = 2 THEN book_local.price*0.2
WHEN [return].ID_condition > book_exemplar_condition.ID_condition AND [return].ID_condition = 3 THEN book_local.price*0.4
WHEN [return].ID_condition > book_exemplar_condition.ID_condition AND [return].ID_condition = 4 THEN book_local.price*0.6
WHEN [return].ID_condition > book_exemplar_condition.ID_condition AND [return].ID_condition = 5 THEN book_local.price*0.8
WHEN (fact_date_of_return is NULL) THEN 0
END AS fine2,
(fine1 + fine2) AS fine
FROM book_global INNER JOIN
book_local ON book_local.ID_book_global = book_global.ID_book_global INNER JOIN
book_exemplar ON book_exemplar.ID_book_local = book_local.ID_book_local INNER JOIN
book_exemplar_condition ON book_exemplar_condition.ID_book_exemplar = book_exemplar.ID_book_exemplar INNER JOIN
condition ON condition.ID_condition = book_exemplar_condition.ID_condition INNER JOIN
issuance ON issuance.ID_book_exemplar = book_exemplar.ID_book_exemplar INNER JOIN
[return] ON [return].ID_issuance = issuance.ID_issuance
所以...(fine1 + fine2)AS很好用。我该如何解决这个问题?
答案 0 :(得分:2)
一种简单的方法是使其他投影成为子查询的一部分
> df[ order(df), c(1,1) ] # I want this but without the a.1 column!!!!
a a.1
4 1 1
3 2 2
8 2 2
1 3 3
5 3 3
6 6 6
7 7 7
10 8 8
另一种方法是实际上对你的两个案例陈述求和,但它可能变得难看
答案 1 :(得分:0)
您可以这样做:
SELECT *, (fine1 + fine2) AS fine
from (
return.ID_issuance,
CASE WHEN DATEDIFF(d, date_of_return, fact_date_of_return) <= 0 THEN 0
WHEN (fact_date_of_return is NULL) THEN book_local.price
ELSE DATEDIFF(d,date_of_return, fact_date_of_return) * 30
END AS fine1,
CASE WHEN [return].ID_condition > book_exemplar_condition.ID_condition AND [return].ID_condition = 2 THEN book_local.price*0.2
WHEN [return].ID_condition > book_exemplar_condition.ID_condition AND [return].ID_condition = 3 THEN book_local.price*0.4
WHEN [return].ID_condition > book_exemplar_condition.ID_condition AND [return].ID_condition = 4 THEN book_local.price*0.6
WHEN [return].ID_condition > book_exemplar_condition.ID_condition AND [return].ID_condition = 5 THEN book_local.price*0.8
WHEN (fact_date_of_return is NULL) THEN 0
END AS fine2
) X
使用派生表,您可以参考结果集中的sum和其他计算列。
其他选项使用外部申请或CTE。