查找顾客购买过的所有商店

时间:2021-02-16 18:33:37

标签: sql sql-server

我有一张包含所有交易信息的表格

<块引用>

(交易日期、客户姓名、交易金额、单位金额、店铺 ID)。

如何创建一个可以正确显示客户访问过的商店的表格?客户可以从多个商店购买,因此客户和商店之间的关系应该是一对多的。我正在尝试检查每位客户访问过的商店。

示例: 交易表

  • store_ID
  • 交易日期
  • 客户姓名
  • 交易金额
  • transaction_unit

预期产出

  • 客户姓名
  • store_list

这只是一个假设问题。也许单独列出所有购物的商店会更好? (但我想如果我们想检查在这些商店购买的客户,这可能会造成混乱)。提前致谢:)

1 个答案:

答案 0 :(得分:0)

由于您已经有一个包含所有所需信息的表,因此您可能需要一个视图,以避免非规范化/重复的数据。

示例如下所示。这里我将使用 sqlite 语法(text 而不是 varchar 等)。我们正在规范化数据以避免出现问题 - 例如,您显示了一个包含客户名称的表,但不同的客户可以具有相同的名称,因此我们使用 customer_id 代替。

首先是表格:

create table if not exists store (id integer primary key, name text, address text);

create table if not exists customer (id integer, name text, document integer);

create table if not exists unit (symbol text primary key);
insert into unit values ('USD'),('EUR'),('GBP'); -- static data

create table if not exists transact (id integer primary key, store_id integer references store(id), customer_id integer references customer(id), transaction_date date, amount integer, unit text references unit(symbol));

-- transaction is a reserved word, so transact was used instead

现在视图:

-- store names concatenated with ',' using sqlite's group_concat
create view if not exists stores_visited as select cust.name, group_concat(distinct store.name order by store.id) from transact trx join customer cust on trx.customer_id=cust.id join store on trx.store_id=store.id group by cust.name order by cust.id;

-- second version, regular select with multiple lines
-- create view if not exists stores_visited as select cust.id, cust.name, store.id, store.name from transact trx join customer cust on trx.customer_id=cust.id join store on trx.store_id=store.id;

示例数据:

insert into store values
  (1,'store one','address one'),
  (2,'store two','address two')
  (3,'store three','address three');

insert into customer values
  (1,'customer one','custdoc one'),
  (2,'customer two','custdoc two'),
  (3,'customer three','custdoc three');

insert into transact values
  (1,1,1,date('2021-01-01'),1,'USD'),
  (2,1,1,date('2021-01-02'),1,'USD'),
  (3,1,2,date('2021-01-03'),1,'USD'),
  (5,1,3,date('2021-01-04'),1,'USD'),
  (6,2,1,date('2021-01-05'),1,'USD'),
  (7,2,3,date('2021-01-06'),1,'USD'),
  (8,3,2,date('2021-01-07'),1,'USD');

测试:

select * from stores_visited;

-- customer one|store one,store one,store two
-- customer three|store one,store two
-- customer two|store one