![](/img/trans.png)
[英]How can I subtract 2 string type times in MM/DD/YYYY HH:MM using SQL?
[英]How can i subtract in a SQL
我知道如何在sql中減去,但在我的情況下有點困難。
我有以下數據庫
表格1
id........artnumber.......price.......flag.......cid
1 12345001 1200 L 9999
2 12345002 2000 L 9999
3 12345003 500 L 7777
4 12345004 1950 L 6666
5 54321001 500 R 9999
6 54321002 1000 R 6666
7 54321003 500 R 9999
表2
id........artnumber.......comment
1 54321001 12345001
2 54321002 12345004
3 54321003 12345001
什么我嘗試的是:我要選擇在此我想從一個以L標志減去與R標志的價格從結果表1為-l標志所有entrys。 但僅限於在表2的注釋中具有其artnumber的那個人
我想要的結果是
artnumber.......price.......flag.......cid
12345001 200 L 9999 //her was 2 R flagged items substracted
12345002 2000 L 9999 //her was nothing substracted
12345003 500 L 7777 //her was nothing substracted
12345004 950 L 6666 //her was 1 R flagged item substracted
有誰知道如何為此設置一個sqlstatement?
我在其他線程上找到了一些,但並沒有真正幫助我:)
這是您的L價格數據:
select l.artnumber, l.price, l.flag
from table1 l
where l.flag = 'L';
這是您的R價格數據:
select x.comment as artnumber, sum(r.price)
from table1 r
inner join table2 x on x.artnumber = r.artnumber
where r.flag = 'R';
一起:
select
l_data.artnumber,
l_data.price - (case when r_data.sum_price is null then 0 else r_data.sum_price end) as calc_price,
l_data.flag,
l_data.cid
from
(
select l.artnumber, l.price, l.flag, l.cid
from table1 l
where l.flag = 'L'
) l_data
left join
(
select x.comment as artnumber, sum(r.price)
from table1 r
inner join table2 x on x.artnumber = r.artnumber
where r.flag = 'R'
) r_data on r_data.artnumber = l_data.artnumber;
這似乎有點時髦,但是可以。 我認為這將為您提供所需的東西:
SELECT a.artnumber, a.price - SUM(IFNULL(b.price, 0)) price, a.flag, a.cid
FROM Table1 a
LEFT JOIN (Table1 b INNER JOIN Table2 ON Table2.artnumber = b.artnumber AND b.flag = 'R')
ON Table2.comment = a.artnumber
WHERE a.flag = 'L'
GROUP BY a.artnumber, a.price, a.flag, a.cid
讓我知道是否需要我解釋其中的任何一個,但是聯接應該非常簡單。
另外,根據您的類型,我不確定您是否必須CAST
該注釋字段才能進行匹配。 那里可能有一些注意事項。 我還假設您的記錄具有唯一性。 換句話說,我認為artnumber
和flag
共同構成一個唯一記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.