来自一个表的股票分类账查询

时间:2013-05-03 09:22:49

标签: sql tsql

我有一张桌子

DocumentNumber, ItemNumber, Qty,
-----------------------------------
600000001,  1006YL01,   1
100001976,  1006YL01,   -1
100008439,  1006YL08,   -1
600000001,  1006YL08,   1
100005095,  1006YL08,   -1
100003814,  1006YL08,   -1
100002955,  1006YL08,   -1
500000087,  1006YL08,   2
500000212,  1006YL08,   1
100001152,  1006YL09,   -1
100004799,  1006YL09,   -1
500000282,  1006YL09,   2
100002859,  1006YL09,   -1
600000001,  1006YL09,   2
100003625,  1006YL09,   -1
600000001,  1006YL10,   2
100003274,  1006YL10,   -1
100002451,  1006YL10,   -1

我想创建一个返回

的查询
Document Number, ItemNumber, ReceiveQty (from qty >1), Issue Qty (from qty<1)

任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

SELECT  DocumentNumber, 
        ItemNumber,
        SUM(CASE WHEN qty > 1 THEN 1 ELSE 0 END) Total_LessThanOne,
        SUM(CASE WHEN qty < 1 THEN 1 ELSE 0 END) Total_GreaterThanOne
FROM    TableName
GROUP   BY DocumentNumber, ItemNumber

答案 1 :(得分:0)

试试这个:

SELECT  DocumentNumber
        ,ItemNumber
        ,CASE WHEN Qty > 1 THEN Qty ELSE 0 END ReceiveQty 
        ,CASE WHEN Qty < 1 THEN Qty ELSE 0 END IssueQty
FROM    Table1

See this SQLFiddle

你也可以在MySQL中使用这个:

SELECT  DocumentNumber
        ,ItemNumber
        ,GROUP_CONCAT(CASE WHEN Qty > 1 THEN Qty ELSE 0 END) ReceiveQty 
        ,GROUP_CONCAT(CASE WHEN Qty < 1 THEN Qty ELSE 0 END) IssueQty
FROM    Table1
GROUP   BY DocumentNumber, ItemNumber

See this SQLFiddle