我想为我的库存创建一个小型数据库,但我在挑选 struct 时遇到了一些问题.库存将在一天结束时每日更新.

我面临的问题如下.

我有一张桌子放我的产品,有一个

id, name, price, quantity.

现在我有了另一张桌子来销售,但这是我的问题.我需要什么样的字段.在一天结束时,我想存储这样一条记录:

20       product_x       $ 5,00         $ 100,-
20       product_y       $ 5,00         $ 100,-
20       product_z       $ 5,00         $ 100,-
20       product_a       $ 5,00         $ 100,-
-------------------------------------------------
                                        $ 400,-

那么,我如何在销售记录中对此进行建模.我是否只需要创建一条连接记录,并用逗号分隔产品ID.

或者有没有另一种方式,以正确的方式建模.

推荐答案

我会有一个每天每件物品一行的表-存储日期、物品ID、售出数量和销售价格(即使它也在产品表中-如果它发生变化,您希望保留您在产品表中的实际销售价值).您可以在查询中计算每个项目的合计和每天的合计.

表:

create table product (
  id integer primary key,
  name varchar(100) not null,
  price decimal(6,2) not null,
  inventory integer not null
);

create table sale (
  saledate date not null,
  product_id integer not null references product,
  quantity integer not null,
  price decimal(6,2) not null,
  primary key (saledate, product_id)
);

每日报道:

select s.product_id, p.name, s.quantity, s.price, (s.quantity * s.price) as total
from product p, sale s
where p.id = s.product_id
and s.saledate = date '2010-12-5';

全天报道:

select saledate, sum(quantity * price) as total
from sale
group by saledate
order by saledate;

一份完整的主报告,包括一行摘要:

select *
from (
    (select s.saledate, s.product_id, p.name, s.quantity, s.price, (s.quantity * s.price) as total
    from product p, sale s
    where p.id = s.product_id)
  union
    (select saledate, NULL, 'TOTAL', sum(quantity), NULL, sum(quantity * price) as total
    from sale group by saledate)
) as summedsales
order by saledate, product_id;

Database相关问答推荐

避免数据库联接的两个查询替换

SearchView 在 Android Studio 中显示 Data.entity.Cantact.@85c7ce6

如何使用 Gramex FormHandler 动态(在运行时)创建或更改数据库模式

安装 SQL Server Management Studio Express后提示:Cannot open user default database. Login failed.

递归关系的数据库设计

MS Access:如何在 VBA 中压缩当前数据库

区分大小写的数据库有什么好处吗?

Zend 框架 - 为什么我应该使用数据映射器/Db_Table_Row?

CouchDB 和 Lotus Notes 有什么区别?

Neo4j:逐步创建自动索引

Hibernate 的 MariaDB 方言类名称是什么?

是否有标准的Electron 商务数据库架构来将折扣/税收/礼券应用于产品?

在 SQL Server 中,如何以类似于 Oracle 的SELECT FOR UPDATE WAIT的方式锁定单行?

SQL Server 2005 是否具有与 MySql 的 ENUM 数据类型等效的数据类型?

寻找示例数据库设计的好方法

您最喜欢在 django 中管理数据库迁移的解决方案是什么?

在 PostgreSQL 中索引空值

如何解析来自 Google 快讯的数据?

获取 SQL Server 2008 中新插入行的主键

无需安装的轻量级 SQL 数据库