我正在SQL Server中的一个项目上工作,我需要查找多少订单包含多个产品。例如,订单号为1,对于样式a,它有多个记录1,对于样式b,它有一个记录。我需要找出同时包含两种样式(a和b或a和c)的订单
select distinct(ordernumber), Style
from table1
join table2 on join1 = join1
where Style in ('a','b','c')
order by ordernumber
我希望将数据导入Excel进行分析,并查看包含我所讨论组合的订单数量。
ordernumber style
1 a
1 b
2 c
2 a
我想看看有多少订单具有多种样式。
答案 0 :(得分:0)
您需要首先查找具有多个产品的订单号,然后查找所有这些订单ID的详细信息。您可以检查以下脚本-
SELECT * FROM Table1 A
INNER JOIN table2 B ON A.<Joining Column> = B.<Joining Column>
WHERE A.ordernumber IN
(
--This query will return Order Numbers that have at least
--2 style in the order details table
SELECT C.ordernumber
FROM table1 C
INNER JOIN table2 D ON C.<Joining Column> = D.<Joining Column>
WHERE Style IN ('a','b')
GROUP BY C.ordernumber
HAVING COUNT(DISTINCT Style) = 2
UNION
SELECT C.ordernumber
FROM table1 C
INNER JOIN table2 D ON C.<Joining Column> = D.<Joining Column>
WHERE Style IN ('a','C')
GROUP BY C.ordernumber
HAVING COUNT(DISTINCT Style) = 2
)