我试图在同一个日历月内显示一个帐户列表,其中2个相同的产品已经为同一帐户订购。
字段名称:
A/c number,
Order id,
Cust name,
Product,
Purchase date
我使用过GROUP BY和HAVING,但我关注的是返回的记录量。
答案 0 :(得分:0)
SELECT *
FROM TABLE as table2
INNER JOIN table as table1
on table1.product = table2.product AND MONTH(table1.purchase_date) = MONTH(tabl2.purchase_date) AND YEAR(table1.purchase_date) = YEAR(table2.purchase_date)
这应该可以解决问题。
答案 1 :(得分:0)
假设我们没有table names
,并且缺少数据,这里是一个返回所需内容的查询示例。只需将字段/表名更改为您正在使用的任何名称。
SELECT account_name
FROM purchaseTable
JOIN productTable on purchaseTable.product = productTable.id
WHERE MONTH(purchaseTable.purchase_date) = MONTH(productTable.purchase_date)
AND YEAR(purchaseTable.purchase_date) = YEAR(productTable.purchase_date)
HAVING COUNT(*) = 2
GROUP BY account_name;
答案 2 :(得分:0)
我建议两次在同一个表上进行内连接。类似的东西:
SELECT o1.*
FROM orders o1
INNER JOIN orders o2
ON o1.account_num = o2.account_num
AND o1.product_id = o2.product_id
AND MONTH(o1.purchase_date) = MONTH(o2.purchase_date)
AND YEAR(o1.purchase_date) = YEAR(o2.purchase_date)
我只是想指出,您必须同时匹配月份和年份,以避免将2014年1月购买的物品与2015年1月份相匹配
答案 3 :(得分:0)
select *
from accounts
where account_id in (
select o.account_id
from orders as o inner join line_items as li on li.order_id = o.order_id
group by o.account_id, li.product_id, year(o.purchase_date), month(o.purchase_date)
having count(*) = 2
)
虽然您丢失了购买信息,但很容易获得帐户信息。
这是一种方法,可以将信息与order_ids和订单的日历月保持一致:
select *
from
accounts as a inner join
(
select
o.account_id, li.product_id,
year(o.purchase_date) as purchase_yr, month(o.purchase_date) as purchase_mo,
min(o.order_id) as order_id1, max(o.order_id) as order_id2
from orders as o inner join line_items as li on li.order_id = o.order_id
group by o.account_id, li.product_id, year(o.purchase_date), month(o.purchase_date)
having count(*) = 2
) as multiples
on multiples.account_id = a.account_id