2012-06-25 76 views
0

我目前的項目是根據下表生成支出報告。完整的報告顯示通過特許經營的零售類別用戶的消費$擊穿,如從下表中生成支出報告

用戶1個

retail_category 1:$ 20

retail_category 2:$ 30

retail_category 3:$ 35

用戶2

retail_category 1:$ 10

retail_category 2:$ 15

retail_category 3:$ 5

下面是表:

class User(models.Model): 
    id_user = models.AutoField(primary_key = True) 

class Franchises(models.Model): 
    id_franchise = models.AutoField(primary_key=True) 
    retail_category = models.IntegerField(default=99) # values are 1 to 13 

class Stores(models.Model): 
    id_store = models.AutoField(primary_key=True) 
    franchise = models.ForeignKey(Franchises, db_column='id_franchise') 

class Receipts(models.Model): 
    id_receipt = models.AutoField(primary_key=True) 
    store = models.ForeignKey(Stores, db_column='id_store') 
    user = models.ForeignKey(User, db_column='id_user') 
    grand_total = models.DecimalField(max_digits=19, decimal_places=4) 

我明白任何原始MySQL或django的模型查詢。謝謝,

回答

0

希望我翻譯你的Django模式規範到原MySQL的正確:

SELECT user, retail_category, SUM(grand_total) 
FROM Receipts 
INNER JOIN Stores ON Receipts.store = Stores.id_store 
INNER JOIN Franchises ON Stores.franchise = Franchises.id_franchise 
GROUP BY user, retail_category; 
+0

它的工作原理,除非你需要內部聯接用戶對receipts.user ID =用戶ID。謝謝 –