简体   繁体   中英

Perform SQL function on single column based on multiple foreign keys

I encounter this problem when trying to work out a dimensional database design. Basicially I haave a fact table (sale_fact) which contains a surrogate key, several foreign keys (pid for product id, cid for country id and date), and sales data. The granularity or this fact table is on daily basis. How do I sum up the sales data for weeks (or months), depending on different combinations of those foreign keys? For example, I want to sum up sales data of product 1 in country 1 in this week (pid = 1 and cid = 1 and date = Monday), sales data of product 2 in country 2 in the same week (pid = 2 and cid = 2 and date = Monday). How do I achieve this data in one SQL? The sample result set would be like:

    | id | pid | cid |     date     | total |
    | 1  |  1  |  1  |  2013-11-04  |   100 |
    | 2  |  1  |  2  |  2013-11-04  |  90   |
    | 3  |  1  |  3  |  2013-11-04  |  80   |
    | 4  |  2  |  1  |  2013-11-04  |  91   |

......more data

您为什么不使用从表中选择sum(sales)作为“总计”之类的方法,其中date = Monday groupby pid,cid ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM