지출-액수.csv month by month ITEM sum by R

library(RSQLite)
library(DBI)
library(tidyr)  # For reshaping the data
library(readr)  # For exporting data to CSV

# Define the path to your SQLite database
db_path <- "/home/jbyungrokim/CSV/CSV.db"

# Connect to the SQLite database
conn <- dbConnect(RSQLite::SQLite(), dbname = db_path)

# Adjust the query to calculate the sum for each item by year and month
query <- "
SELECT 
    strftime('%Y-%m', '20' || substr(Date_Transaction, 7, 2) || '-' || substr(Date_Transaction, 1, 2) || '-' || substr(Date_Transaction, 4, 2)) AS YearMonth,
    Item, 
    SUM(Pay_Amount) AS Total_Spent
FROM 
    '지출-액수_2024_08_20'
GROUP BY 
    YearMonth, Item
ORDER BY 
    YearMonth, Total_Spent DESC;
"

# Execute the query and store the result in a data frame
monthly_sum <- dbGetQuery(conn, query)

# Print the result
print("Sum of Pay_Amount by Item for each Year/Month:")
print(monthly_sum)

# Reshape the data into a wide format for better readability in a spreadsheet
monthly_sum_wide <- spread(monthly_sum, YearMonth, Total_Spent, fill = 0)

# Export the data to a CSV file
output_path <- "/home/jbyungrokim/CSV/monthly_sum_by_item.csv"
write_csv(monthly_sum_wide, output_path)

# Print the location of the saved file
print(paste("Data has been saved to:", output_path))

# Close the connection to the SQLite database
dbDisconnect(conn)

Leave a Reply

Your email address will not be published. Required fields are marked *