您好我有这个查询,而我正在尝试实现列NextColumn
中的行数将是列z
中具有相同值的行数。我认为可以这样做:
(SELECT COUNT(U1.z) GROUP BY U1.z)
但我得到了这个:
Each GROUP BY expression must contain at least one column that is not an outer reference.
SELECT K.name AS Name, K.surname AS Surname, U1.akce AS Event,
U2.[text] AS [Scheme], U1.[text] AS [Registered under], u1.z, NextColumn
FROM klient K
INNER JOIN ubytov U1 ON U1.[text] = K.ubytov
LEFT OUTER JOIN ubytov U2 ON U1.z = U2.id WHERE U1.akce = '140012-02'
ORDER BY U1.[text]
有人会帮我解决这个问题吗?
感谢您的时间。
My data now:
Name z NextColumn
1 8 1
2 8 1
3 7 1
4 7 1
我想根据z
值
Name z NextColumn
1 8 2
2 8 2
3 7 2
4 7 2
使用此查询
with CTE as
(
select Count(u.z) as NextColumn, u.z as Z
from ubytov u
group by u.z
)
select * from CTE
我得到了这些结果:
NextColumn Z
0 NULL
1 34
1 36
1 37
答案 0 :(得分:1)
尝试将NextColumn
改为相关子查询:
SELECT K.name AS Name, K.surname AS Surname, U1.akce AS Event,
U2.[text] AS [Scheme], U1.[text] AS [Registered under], u1.z,
(SELECT COUNT(*) FROM ubytov u3 WHERE u3.z = u1.z) NextColumn
FROM klient K
INNER JOIN ubytov U1 ON U1.[text] = K.ubytov
LEFT OUTER JOIN ubytov U2 ON U1.z = U2.id WHERE U1.akce = '140012-02'
ORDER BY U1.[text]
答案 1 :(得分:1)
另一种可能的解决方案:
with CTE as
(
select Count(u.z) as NextColumn, u.z as Z
from ubytov u
inner join Klients K on u.[text] = K.ubytov
LEFT OUTER JOIN ubytov U2 ON u.z = U2.id WHERE u.akce = '140012-02'
group by u.z
)
SELECT K.name AS Name, K.surname AS Surname, U1.akce AS Event,
U2.[text] AS [Scheme], U1.[text] AS [Registered under], u1.z,
CTE.NextColumn
FROM klient K
INNER JOIN ubytov U1 ON U1.[text] = K.ubytov
INNER JOIN CTE on U1.z = CTE.Z
LEFT OUTER JOIN ubytov U2 ON U1.z = U2.id WHERE U1.akce = '140012-02'
ORDER BY U1.[text]