1

如何在 MySQL 中构造查询来计算组的结果?所以,

表 A

Month    Item
Jan         1
Jan         3
Feb         2
Feb         2
Mar         3

表 B

Item   Color
1       red
1       blue
2       black
3       black
3       yellow

我想要一个查询,它会告诉我表 B 中存在多少表 A 中的项目,其中每个月至少有两种颜色。换句话说,我每个月卖出了多少件超过 2 种颜色的商品。所以结果是:

Month  Results
Jan      2
Feb      0
Mar      1

谢谢你。

4

3 回答 3

2

如果我正确理解了这个问题,我认为以下内容可以回答它:

select a.month,
       (case when count(distinct b.color) >= 2 then COUNT(distinct a.item) else 0 end)
from TableA a join
     TableB b
     on a.item = b.item
group by a.month

这会计算一个月内的颜色总数。如果 2 或更大,则它具有项目数。否则,它有 0。

于 2013-02-04T21:26:39.240 回答
1

此子查询返回至少具有两种颜色的所有项目:

select Item
from TableB
group by Item
having count(distinct Color)>1

您可以将它与 TableA 连接起来,结果查询是这样的:

select
  A.Month,
  Count(B.Item)
from
  TableA A left join (
    select Item
    from TableB
    group by Item
    having count(distinct Color)>1) B
  on A.Item=B.Item
group by A.Month
于 2013-02-04T22:40:46.187 回答
0

Try something like this:

SELECT DISTINCT T.Month, COALESCE(T2.Cnt2,0) Cnt
FROM (
   SELECT Month
   FROM TableA
) T LEFT JOIN (
   SELECT A.Month, COUNT(DISTINCT B.Color) Cnt, COUNT(DISTINCT B.Item) Cnt2
   FROM TableA A
      INNER JOIN TableB B ON A.Item = B.Item
   GROUP BY A.Month
   HAVING  COUNT(DISTINCT B.Color) >= 2
) T2 ON T.Month = T2.Month

It Uses GROUP BY and HAVING to get the COUNT of DISTINCT Items in TableA and TableB. To return Feb 0, you need the LEFT JOIN.

Here is the SQL Fiddle.

Good luck.

于 2013-02-04T21:20:20.530 回答