与不工作的地方分组
SELECT A.ID, A.COLUMN_B, A.COLUMN_C FROM A
WHERE A.COLUMN_A IN
(
SELECT A.COLUMN_A
FROM B
INNER JOIN A ON B."COLUMN_A" = A."COLUMN_A"
WHERE B."COLUMN_B" = 'something'
UNION
SELECT A."COLUMN_A"
FROM A
WHERE A."COLUMN_D" IN (X,Y,Z) OR A."COLUMN_D" = 'something'
)
现在我想添加一个group by (A.ID)
和order by (A.COLUMN_B) DESC
,然后select first
。但DB不允许。有什么建议吗?一旦内部 Union 部分返回,我可以使用 LINQ 来解决它。但现在确实想走那条路。
SELECT A.ID, A.COLUMN_B, A.COLUMN_C FROM A
WHERE A.COLUMN_A IN
(
SELECT A.COLUMN_A
FROM B
INNER JOIN A ON B."COLUMN_A" = A."COLUMN_A"
WHERE B."COLUMN_B" = 'something'
UNION
SELECT A."COLUMN_A"
FROM A
WHERE A."COLUMN_D" IN (X,Y,Z) OR A."COLUMN_D" = 'something'
)
Now I want add a group by (A.ID)
, and order by (A.COLUMN_B) DESC
, and then select first
to it. But DB won't allow. Any suggestions ? I can use LINQ to solve it once inner Union part is returned. But do now want to go that way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里有几件事。
首先 - 在 DB2 中,当使用
GROUP BY
时,您只能选择分组语句中列出的那些列 - 其他所有内容必须是聚合函数的一部分。因此,按a.Id
分组并按a.Column_B
排序将不起作用 - 您需要按SUM(a.Column_B)
排序代码> 或适用的内容。其次......您的查询可能会在一般意义上使用一些工作 - 具体来说,您要自连接两次,而您根本不需要这样做。请尝试以下操作:
将
SUM
函数替换为任何合适的函数。There's a couple of things here.
First off - in DB2, when using
GROUP BY
, you can only select those columns listed in the grouping statement - everything else must be part of an aggregation function. So, grouping bya.Id
and ordering bya.Column_B
won't work - you'll need to order bySUM(a.Column_B)
or something applicable.Second... your query could use a bit of work in the general sense - specifically, you're self-joining twice, which you don't need to do at all. Try this instead:
Swap out the
SUM
function for whatever is appropriate.您不能在 ORDER BY 或 SELECT 中使用未包含在 GROUP BY 中的列,除非正在聚合该列(在 MAX() 或 COUNT() 或 SUM() 等函数中。
因此,您可以 GROUP BY A.ID,A.COLUMN_B,然后 ORDER BY COLUMN_B 也应该可以工作,
我刚刚注意到您在 DB2 上,我知道它会的。 DB2 上的工作方式应该类似。
You can't use a column in the ORDER BY or SELECT that you haven't included in the GROUP BY, unless it's being aggregated (in a function like MAX() or COUNT() or SUM().
So, you could GROUP BY A.ID,A.COLUMN_B, and then ORDER BY COLUMN_B. Using a TOP 1 should work, too.
I just noticed that you're on DB2. I know that it will work this way on SQLServer. DB2 should be similar.
反之亦然。刚刚在 A.ID 上使用了 Order By 并选择具有最大标识列的行。
Worked the oterh way around. Just used Order By on A.ID and select row with max identity column.