需要显示以下使用UNION返回的列(3):
表格:
客户
产品
发票
发票项目
到目前为止有以下内容:
SELECT
category,
CASE
WHEN category = 'customer' THEN c.id
WHEN category = 'product' THEN p.id
END AS 'id',
CASE
WHEN category = 'customer' THEN c.customer_name
WHEN category = 'product' THEN p.product_name
END AS 'name'
FROM
(
SELECT
CASE
WHEN c.id = c.id THEN 'customer'
WHEN p.id = p.id THEN 'product'
END as 'category'
FROM
customer as c
LEFT Join -- Left join to show all customers even those with & without invoices
invoice as i
ON c.id = i.customer_id
AND i.id IS NULL -- Gives me all customers who do not have an invoice
JOIN invoice_item as ii
ON i.id = ii.invoice_id
Join product p
ON p.id = ii.product_id
) tb1
UNION ALL
SELECT
category,
CASE
WHEN category = 'customer' THEN c.id
WHEN category = 'product' THEN p.id
END AS 'id',
CASE
WHEN category = 'customer' THEN c.customer_name
WHEN category = 'product' THEN p.product_name
END AS 'name'
FROM
(
SELECT
CASE
WHEN c.id = c.id THEN 'customer'
WHEN p.id = p.id THEN 'product'
END as 'category'
FROM
product as p
LEFT JOIN -- Left join to show all products even those that sold and not sold
invoice_item as ii
ON p.id = ii.product_id
AND ii.invoice_id IS NULL -- Gives me products that didnt sell
JOIN invoice as i
ON ii.invoice_id = i.id
) tb2
欢迎提出任何建议,因为我一直试图找出如何将类别显示为“产品”或“客户”。预先感谢!
答案 0 :(得分:0)
考虑到您的数据模型和要求,您应该尝试以下SQL。您可以轻松地对两个SQL执行UNION
。
第一个SQL返回此列表->所有没有发票的客户
select 'customer' as category, c.id as id, customer_name as name
from customer c
left join invoice i on c.id = i.customer_id
where i.id is null
第二条SQL返回此列表->所有未售出的产品
select 'product' as category, p.id as id, product_name as name
from product p
left join invoice_item ii on p.id = ii.product_id
where ii.id is null;
答案 1 :(得分:0)
嗯,它已经超过 6 个月了,但答案仍然是:
select 'customer' as category, c.id as id, customer_name as name
from customer c
left join invoice i on c.id = i.customer_id
where i.id is null
union
select 'product' as category, p.id as id, product_name as name
from product p
left join invoice_item ii on p.id = ii.product_id
where ii.id is null;
答案 2 :(得分:0)
实际问题是所有客户的详细信息,即使是没有发票的,所有产品,甚至是未售出的产品。
SELECT c.customer_name,
p.product_name,
Coalesce((ii.quantity), 0) AS quantity
FROM customer c
LEFT JOIN invoice i
on c.id = i.customer_id
LEFT JOIN invoice_item ii
ON ii.invoice_id = i.id
LEFT JOIN product p
ON ii.product_id = p.id
ORDER BY c.customerid,
p.product_id,
ii.id
UNION
SELECT 'N/A',
p.product_name,
0
FROM products p
ORDER BY p.id
答案 3 :(得分:-1)
SELECT 'customer' as category,id,customer_name FROM customer
WHERE id NOT IN(SELECT customer_id FROM invoice)
UNION
SELECT 'product' as category,id,product_name FROM product
WHERE id NOT IN(SELECT product_id FROM invoice_item);