Tags:

ฐานข้อมูล

account (
id, date, doing, money
)

ข้อมูลตัวอย่าง

id, date, doing, money
1, 2017-01-01, refill, 100
2, 2017-01-01, refill, 200
3, 2017-01-01, withdraw, 100,
4, 2017-01-02, withdraw, 200,
5, 2017-01-02, refill, 300,
6, 2017-01-02, withdraw, 100,
7, 2017-01-03, refill, 300,
8, 2017-01-03, refill, 100,
9, 2017-01-03, withdraw, 100

ผมต้องการคำนวนว่าแต่ละวันมีจำนวนเงินฝากและถอนเท่าไหร่
ถ้า select sum group ให้ได้ผลลัพท์แบบนี้
2017-01-01, refill, 300
2017-01-02, refill, 300
2017-01-03, refill, 400
2017-01-01, withdraw, 300
2017-01-02, withdraw, 300
2017-01-03, withdraw, 100

แต่ผมอยากได้ผลลัพท์แบบนี้เลย
2017-01-01, refill, 300, withdraw, 300
2017-01-02, refill, 300, withdraw, 300
2017-01-03, refill, 400, withdraw, 100

โดยใช้ผลลัพท์ออกมาจากคำสั่ง sql เลย จะสามารถทำได้ไหมครับ
บางครั้งแต่ต้องการดูผลใน sql เฉยๆ ไม่อยากเขียนโปรแกรมให้ลงใน array ก่อน
ขอบคุณครับ

Get latest news from Blognone
By: varavut
ContributorWindows PhoneAndroidBlackberry
on 10 July 2017 - 20:15 #997281

ผมว่าน่าจะประมาณ

SELECT date, 
SUM(IF(doing = 'refill', money, 0)) as refill, 
SUM(IF(doing = 'withdraw', money, 0)) as withdraw
FROM account 
GROUP BY date
By: piti
iPhoneWindows PhoneAndroidWindows
on 11 July 2017 - 12:05 #997373

ผมลองดูแบบนี้ให้นะครับ ของผมใช้ SQL Server แต่ไม่แน่ใจว่าทางคุณใช้อะไรนะครับ

CREATE TABLE table1(
id INT,
dy DATETIME,
whattodo VARCHAR(10),
mny INT
);
GO

INSERT INTO table1(id, dy, whattodo, mny)
SELECT 1, '2017-01-01', 'refill', 100
UNION ALL
SELECT 2, '2017-01-01', 'refill', 200
UNION ALL
SELECT 3, '2017-01-01', 'withdraw', 100
UNION ALL
SELECT 4, '2017-01-02', 'withdraw', 200
UNION ALL
SELECT 5, '2017-01-02', 'refill', 300
UNION ALL
SELECT 6, '2017-01-02', 'withdraw', 100
UNION ALL
SELECT 7, '2017-01-03', 'refill', 300
UNION ALL
SELECT 8, '2017-01-03', 'refill', 100
UNION ALL
SELECT 9, '2017-01-03', 'withdraw', 100
GO

SELECT dy, SUM(refill) AS refill, SUM(withdraw) AS withdraw
FROM (
SELECT *
FROM table1
PIVOT (SUM(mny) FOR whattodo IN ([refill], [withdraw])) AS sumOfmny
) AS PivotTable
GROUP BY dy
GO

DROP TABLE table1;

By: waroonh
Windows
on 13 July 2017 - 12:18 #997681

Select
[Date] as Transaction_Date
, 'refill' as Refill_Label
, Sum(Case When [doing] = 'refill' Then [money] Else 0 End) as Sum_Refill
, 'withdraw' as Withdraw_Label
, Sum(Case When [doing] = 'withdraw' Then [money] Else 0 End) as Sum_Refill
from [dbo].[account]
group by [Date]