BizTable
ID From Store To Store Quantity
01020405 401 402 5
01020405 499 406 6
01020405 401 418 15
01020405 403 402 10
01020405 402 403 20
01020405 402 406 10
01020405 406 403 2
我的目标是编写一个查询,显示每个PART的每个PART的概要数量从上面的BizTable中的每个PART和连接存储它在字符串中的TO,如下表所示
ID Store_OUT SUM_Quantity
01020405 401 - 402,418 20
01020405 402 - 403,406 30
答案 0 :(得分:0)
SELECT id, CONCAT(FROM_store,' - ',`to_store`) AS store_out,
SUM(quantity) AS sum_quantity
FROM biztable
GROUP BY id , from_store, to_store
ORDER BY id , from_store, to_store;
答案 1 :(得分:0)
谢谢@ J.Zend。
我错过了to_store专栏。这是正确的查询:
SELECT id, CONCAT(FROM_store,' - ',`to_store`) AS store_out,
SUM(quantity) AS sum_quantity
FROM biztable
GROUP BY id , from_store, to_store
ORDER BY id , from_store, to_store;
有一个问题。 WHS-OUT列未在连接结果中添加所有to_stores,如示例所示。此查询仅使用一个商店。
答案 2 :(得分:0)
表架构
CREATE TABLE TESTXML
(
ID VARCHAR(20),
FromStore VARCHAR(20),
ToStore VARCHAR(20),
Quantity INT
)
INSERT INTO TESTXML
VALUES( '01020405','401','402',5),
( '01020405','499','406',6),
( '01020405','401','418',15),
( '01020405','403','402',10),
( '01020405','402','403',20),
( '01020405','402','406',10),
( '01020405','406','403',2)
现在试试这个
;WITH CTE AS
(
SELECT
ID,
FromStore,
ToStore,
STORE_OUT =
(
SELECT [text()] = A.ToStore + ','
FROM TestXml A
WHERE A.FromStore = B.FromStore
ORDER BY A.ToStore
FOR XML PATH('')
)
FROM TestXml B
)
,BTE AS
(
SELECT X.ID, X.FromStore, X.FromStore+' - '+X.STORE_OUT AS STORE_OUT , Y.Quantity
FROM CTE X
JOIN TestXml Y ON X.ID = Y.ID AND X.FromStore = Y.FromStore AND X.ToStore = Y.ToStore
)
SELECT ID, LEFT(STORE_OUT, (LEN(STORE_OUT) - 1)) AS Store_Out, SUM(Quantity) AS SUM_Quantity
FROM BTE
GROUP BY ID, STORE_OUT
您将获得以下结果
ID Store_Out Sum_Quantity
01020405 401 - 402,418 20
01020405 402 - 403,406 30
01020405 403 - 402 10
01020405 406 - 403 2
01020405 499 - 406 6