我最近用几个新表更改了我的数据库更新,并且无法从三个不同的表中获取(选择)数据
有4家商店相互交换库存,它被记录在数据库中。
表'sites'有商店ID和名称信息。
CREATE TABLE `sites` (
`id` int(10) NOT NULL,
`name` varchar(35) NOT NULL
)
表' stock_exchange_new '包含有关库存转移日期的信息 商店,商店等。
CREATE TABLE `stock_exchange_new` (
`id` int(11) NOT NULL,
`transfer_date` date NOT NULL,
`from_site` int(11) NOT NULL,
`to_site` int(11) NOT NULL,
`transfer_ref` varchar(255) NOT NULL,
`note` varchar(300) NOT NULL,
`added_by` int(11) NOT NULL,
`added_at` datetime NOT NULL,
`edited_by` int(11) NOT NULL,
`edited_at` datetime NOT NULL
)
表' stock_item_txns '包含有关项目的信息 交换/转移:
CREATE TABLE `stock_item_txns` (
`id` int(11) NOT NULL,
`stock_exchange_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
`units_per_ctn` int(11) NOT NULL,
`qty` decimal(10,2) NOT NULL,
`ctn_price` decimal(10,2) NOT NULL,
`total_price` decimal(10,2) NOT NULL
)
现在,对于一个特定的商店,我需要显示的数据与自身比较,例如:对于商店1,它应该是这样的:
Store Name Total_Sent Total_Received
Store2 500 200
Store3 490 580
Store4 300 400
到目前为止试过......
SELECT GREATEST(s1.name, s2.name) AS from_store,
LEAST(s1.name, s2.name) AS to_store,
SUM(CASE WHEN s1.name < s2.name THEN si.total_price ELSE 0 END) AS received,
SUM(CASE WHEN s1.name > s2.name THEN si.total_price ELSE 0 END) AS sent
FROM stock_exchange_new se
INNER JOIN sites s1
ON se.from_site = s1.id
INNER JOIN sites s2
ON se.to_site = s2.id
INNER JOIN stock_item_txns si
ON se.id = si.stock_exchange_id
GROUP BY GREATEST(se.from_site, se.to_site),
LEAST(se.from_site, se.to_site)
HAVING MAX(GREATEST(se.from_site, se.to_site)) = '1'
以下是fiddle,以便更好地理解。
答案 0 :(得分:1)
利用几个子查询,类似这样(未经测试): -
SELECT s2.name AS 'Store Name',
from_site_total,
to_site_total
FROM sites s1
CROSS JOIN sites s2
LEFT OUTER JOIN
(
SELECT from_site,
to_site,
SUM(stock_item_txns.total_price) AS from_site_total
FROM stock_exchange_new
INNER JOIN stock_item_txns ON stock_exchange_new.id = stock_item_txns.stock_exchange_id
GROUP BY from_site,
to_site
) sub_from_site
ON s1.id = sub_from_site.from_site
AND s2.id = sub_from_site.to_site
LEFT OUTER JOIN
(
SELECT to_site,
from_site,
SUM(stock_item_txns.total_price) AS to_site_total
FROM stock_exchange_new
INNER JOIN stock_item_txns ON stock_exchange_new.id = stock_item_txns.stock_exchange_id
GROUP BY to_site,
from_site
) sub_to_site
ON s1.id = sub_to_site.to_site
AND s2.id = sub_to_site.from_site
WHERE s1.name = 'Store1'
AND s2.name != 'Store1'