0

我有以下 SQL 查询:

SELECT 
kvknum.cd_hfdrelnr, 
kvknum.cd_kvkanum,
    relName.cd_hfdrelnr
FROM
(
    SELECT 
        cd_hfdrelnr, 
        cd_kvkanum

FROM er_105
WHERE cd_kvkanum IN
(
    SELECT cd_kvkanum
    FROM er_105
    GROUP BY cd_kvkanum
    HAVING COUNT(*) > 1 
)
AND cd_kvkanum != ''
ORDER BY cd_kvkanum
) AS kvknum
LEFT OUTER JOIN
(
    SELECT 
        cd_hfdrelnr,
        cd_relnaam
    FROM er_101
) AS relName
ON kvknum.cd_hfdrelnr = relName.cd_hfdrelnr

GROUP BY功能是不允许的,并且需要它,因此相同的cd_kvkanum值在彼此下方一起显示,是否有解决此问题的方法或如何实现?

随之而来的错误如下:

“消息 1033,级别 15,状态 1,第 21 行 ORDER BY 子句在视图、内联函数、派生表、子查询和公用表表达式中无效,除非还指定了 TOP 或 FOR XML。消息 156,级别 15,状态1,第 28 行关键字 'AS' 附近的语法不正确。”

当我运行以下查询时:

SELECT 
    cd_hfdrelnr, 
    cd_kvkanum

FROM er_105
WHERE cd_kvkanum IN
(
    SELECT cd_kvkanum
    FROM er_105
    GROUP BY cd_kvkanum
    HAVING COUNT(*) > 1 
)
AND cd_kvkanum != ''
ORDER BY cd_kvkanum

(连接的第一个子查询)结果如下:
1235 - 123
4652 - 123
8569 - 1234
4985 - 1234

虽然我想将 cd_relnaam 添加到结果列表中,但是当在查询上使用 JOIN 时,我的结果是空白的......

有人知道我做错了什么吗?

4

2 回答 2

1

这不是一个完整的答案,但是,如果我没记错的话,您的查询可以写得更简单。当人们可以编写简单的查询时,90% 的错误会出现在他们编写非常复杂的查询时。简单是成功的关键:) 当你给出更确切的问题时,我会编辑答案

SELECT 
    kvknum.cd_hfdrelnr, 
    kvknum.cd_kvkanum,
    relName.cd_hfdrelnr
FROM er_105 as kvknum
    LEFT OUTER JOIN er_101 as relName on relName.cd_hfdrelnr = kvknum.cd_hfdrelnr
where
    kvknum.cd_kvkanum IN
    (
        SELECT cd_kvkanum
        FROM er_105
        GROUP BY cd_kvkanum
        HAVING COUNT(*) > 1 
    ) AND
    cd_kvkanum != ''
于 2012-10-19T06:55:29.513 回答
1

这里的问题不在于 GROUP BY,实际上是 ORDER BY,你不能把它放在子查询中,它必须在你的父查询中。另外,我的理解是,您需要 er_105 中的记录,其中 cd_kvkanum 出现多次并且不是空白的,但您不想汇总。

SELECT er_105.cd_hfdrelnr, 
       er_105.cd_kvkanum,
       er_101.cd_relnaam
  FROM er_105
  JOIN (SELECT cd_kvkanum,COUNT(cd_kvkanum)
          FROM er_105
         WHERE cd_kvkanum != ''
      GROUP BY cd_kvkanum
        HAVING COUNT(cd_kvkanum) > 1
       ) kvknum ON er_105.cd_kvkanum = kvknum.cd_kvkanum
LEFT JOIN er_101 ON er_105.cd_hfdrelnr = er_101.cd_hfdrelnr
 ORDER BY er_105.cd_kvkanum

通常,当您想计算某事的出现次数时,最好执行 SELECT something,COUNT(PrimaryKey) 而不是 COUNT(*)。* 使 SQL 做了额外的步骤来弄清楚 * 代表什么。当然,就像 stackoverflow 上的许多查询一样,总是有一种更简单的方法来编写它;)

于 2012-10-19T08:24:23.003 回答