我的内部查询工作正常,但是当我按功能使用分组时,出现错误"Column 'b.id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."
我已经使用了多种技巧,但是没有一个起作用(像不同的一样)
select * from (
SELECT tsr.id,tblstckid,ts.articleNo,ts.code,size,ts.insertDate FROM [tbl_setsRegister] tsr
APPLY dbo.Split1(tsr.tblstckid, ',') AS htvf
inner join tbl_stock ts on ts.id=htvf.Item where ts.id not in(60,62) and ts.articleNo='121010' and code='unknown-1')
group by b.tblstckid
我想要从tblstckid中获得与其他列不同的值
样本数据
id tblstckid articleNo cCode size insertDate
21 55,56,58, 121010 unknown-1 34 2018-09-20 19:44:00.000
21 55,56,58, 121010 unknown-1 36 2018-09-20 19:44:00.000
21 55,56,58, 121010 unknown-1 38 2018-09-20 19:44:00.000
22 57, 121010 unknown-1 36 2018-09-20 19:44:00.000
23 59,61,63, 121010 unknown-1 34 2018-09-20 19:46:00.000
23 59,61,63, 121010 unknown-1 36 2018-09-20 19:46:00.000
我要删除重复的tblstckid
答案 0 :(得分:3)
您必须将SELECT列表的所有列(除聚合列之外)放入GROUP BY。当您选择所有内容但仅在GROUP BY中放入一列时,会引发错误
SELECT b.tblstckid
FROM (
SELECT tsr.id, tblstckid, ts.articleNo, ts.code, size, ts.insertDate
FROM [tbl_setsRegister] tsr
APPLY dbo.Split1(tsr.tblstckid, ',') AS htvf
INNER JOIN tbl_stock ts
ON ts.id = htvf.Item
WHERE ts.id NOT IN(60,62) AND ts.articleNo = '121010' AND code = 'unknown-1'
) b
GROUP BY b.tblstckid
但是,由于您没有任何聚合函数,但是您使用了令人困惑的GROUP BY
您可以使用row_number
SELECT * FROM
(
SELECT tsr.id, tblstckid, ts.articleNo, ts.code, size, ts.insertDate,
ROW_NUMBER() OVER(
PARTITION BY tsr.id, tblstckid, ts.articleNo, ts.code, ts.insertDate
ORDER BY size
) AS rn
FROM [tbl_setsRegister] tsr
APPLY dbo.Split1(tsr.tblstckid, ',') AS htvf
INNER JOIN tbl_stock ts
ON ts.id = htvf.Item
WHERE ts.id NOT IN(60,62) AND ts.articleNo = '121010' AND code = 'unknown-1'
) b
WHERE b.rn=1
答案 1 :(得分:0)
您必须将聚合函数应用于不在GROUP BY子句中的所有列。可能的解决方案是:
SELECT
id, tblstckid, articleNo, code,
SUM(size) AS tot_size, MAX(ts.insertDate) AS lastInsertDate
FROM (
SELECT tsr.id, tblstckid, ts.articleNo, ts.code, size, ts.insertDate
FROM [tbl_setsRegister] tsr
APPLY dbo.Split1(tsr.tblstckid, ',') AS htvf
INNER JOIN tbl_stock ts
ON ts.id = htvf.Item
WHERE ts.id NOT IN(60,62) AND ts.articleNo = '121010' AND code = 'unknown-1'
) b
GROUP BY id, tblstckid, articleNo, code
您必须确定哪个聚合函数最有意义。如果要保留所有值,也可以使用STRING_AGG
STRING_AGG (CAST(size AS varchar(10), ', ') AS sizes