1

大家好,提前感谢您的帮助。这是我的场景:

我有三个链接表,显示每个表中使用的生产规格和墨水类型。每个规格可以有可变数量的墨水(从 1 到 10),这些墨水可能与其他规格相同,也可能不同。我的目标是让每个规范都能够显示规范名称和出现频率更高的墨水。

例如规格 XYZ:

|=====|=====|
¦SPEC ¦INK  ¦
|=====|=====|
¦XYZ  ¦blue ¦
¦XYZ  ¦red  ¦
¦XYZ  ¦red  ¦
¦XYZ  ¦red  ¦
¦XYZ  ¦brown¦
|=====|=====|

我只想显示:

|=====|=====|
¦SPEC ¦INK  ¦
|=====|=====|
¦XYZ  ¦red  ¦
|=====|=====|

这些表链接如下:

SELECT tblStudioInput.SpecNo
    , tblListInkSystem.Ink
FROM tblStudioInput
INNER JOIN tblStudioInputColour
    ON tblStudioInput.stID = tblStudioInputColour.StudioInputID
INNER JOIN tblListInkSystem
    ON tblStudioInputColour.InkSystem = tblListInkSystem.ID

再次提前感谢大家

4

2 回答 2

2
SELECT SPEC, INK
FROM
  (
    SELECT SPEC, INK,
           DENSE_RANK() OVER (ORDER BY COUNT(*) DESC) rn
    FROM Table1
    GROUP BY SPEC, INK
  ) s
WHERE rn = 1

资源

于 2012-11-22T00:15:31.373 回答
0

[更新] 你可以试试这个:

select top 1 with ties
    spec, ink
from
    (
      select
          spec, ink, count(*) n
      from
          tmp
      group by
          spec, ink
    ) t
order by
    n desc

[更新] SQLFiddle 演示

或者没有排序

with q as (
    select
        spec, ink, count(*) n
    from
        tmp
    group by
        spec, ink
)

select
    spec, ink
from
    q
where
    n = (
        select
            max(n)
        from
            q
    )

或没有 CTE

select
    spec, ink
from
    tmp
group by
    spec, ink
having
    count(*) = (
        select
            max(n)
        from
            (
                select
                    count(*) n
                from
                    tmp
                group by
                    spec, ink
            ) t
    )
于 2012-11-22T10:38:45.087 回答