我有以下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
值相互显示,是否可以解决此问题或者如何实现?
出现以下错误:
“Msg 1033,Level 15,State 1,Line 21 除非还指定了TOP或FOR XML,否则ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效。 Msg 156,Level 15,State 1,Line 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时,我的结果是空白的......
有谁知道我做错了什么?
答案 0 :(得分: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 != ''
答案 1 :(得分: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事物,COUNT(PrimaryKey)而不是COUNT(*)会更好。 *使SQL做出额外的步骤,找出*代表什么。当然,就像stackoverflow上的许多查询一样,总是有一种更简单的方法来编写它;)