library(RSQLite)
library(DBI)
library(ggplot2)
# 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 in September 2024
query <- "
SELECT
Item,
SUM(Pay_Amount) AS Total_Spent
FROM
'지출-액수_2024_09_14'
WHERE
strftime('%Y-%m', '20' || substr(Date_Transaction, 7, 2) || '-' || substr(Date_Transaction, 1, 2) || '-' || substr(Date_Transaction, 4, 2)) = '2024-09'
GROUP BY
Item
ORDER BY
Total_Spent DESC;
"
# Execute the query and store the result in a data frame
September_2024_sum <- dbGetQuery(conn, query)
# Print the result
print("Sum of Pay_Amount by Item for September 2024:")
print(September_2024_sum)
# Save the result as a CSV file
csv_file_path <- "/home/jbyungrokim/Downloads/September_2024_sum.csv"
write.csv(September_2024_sum, file = csv_file_path, row.names = FALSE)
print(paste("Data has been written to", csv_file_path))
# Create a bar graph using ggplot2
ggplot(September_2024_sum, aes(x = reorder(Item, -Total_Spent), y = Total_Spent)) +
geom_bar(stat = "identity", fill = "steelblue") +
theme_minimal() +
labs(title = "Total Spending by Item for September 2024",
x = "Item",
y = "Total Spent ($)") +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
# Close the connection to the SQLite database
dbDisconnect(conn)