简体   繁体   English

选择不同的值,其中条件总和 < 值

[英]Select distinct values where condition having sum < value

I have a problem with a SQL query.我的 SQL 查询有问题。 I need to get a list of all unique [Cod Angajat] field for which the sum of all entries in the column [Timp declarat] is less than 8, with the where clause.我需要使用 where 子句获取所有唯一 [Cod Angajat] 字段的列表,其中 [Timp declarat] 列中所有条目的总和小于 8。 Bellow is what I've gotten so far.波纹管是我到目前为止所得到的。

In the table I have 3 rows.在表中我有 3 行。 It returns me the same rows, instead of 1 row, for which all the conditions apply - meaning the one with [Cod Angajat] = 2.它返回相同的行,而不是 1 行,所有条件都适用 - 意味着 [Cod Angajat] = 2 的行。

|   Cod Angajat  |   Nume   |  Timp declarat  |
---------------------
|  1             |  Ene     | 3               |
|  1             |  Ene     | 5               |
|  2             |  Gigi    | 4               |
select COUNT(DISTINCT [Cod Angajat]), [Cod Angajat], [Nume], [Timp declarat]
FROM [SC Vermorel SRL$ProductieVE]
WHERE (sum([Timp declarat] < 8 AND cast(CONVERT(varchar(8), Data, 112) As DateTime) = @data2) and ([Schimb] = '" & ProceseazaSCH(Now()) & "' 
GROUP BY [Nume], [Cod Angajat], [Timp declarat]
HAVING sum([Timp declarat]) < 8

With the query you are grouping by Timp declarat which is why you have duplicates of Cod Angajat in your return set.通过查询,您按 Timp declarat 分组,这就是为什么您的返回集中有 Cod Angajat 重复的原因。 Since everywhere else in the query is using the Sum of Timp Declarat I would assume the below is what you require:由于查询中的其他地方都在使用 Timp Declarat 的总和,我认为以下是您所需要的:

select COUNT(DISTINCT [Cod Angajat]), [Cod Angajat], [Nume], SUM([Timp declarat]) as SumTimpDeclarat
FROM [SC Vermorel SRL$ProductieVE]
WHERE (sum([Timp declarat] < 8 AND cast(CONVERT(varchar(8), Data, 112) As DateTime) = @data2) and ([Schimb] = '" & ProceseazaSCH(Now()) & "' 
GROUP BY [Nume], [Cod Angajat]
HAVING sum([Timp declarat]) < 8

If you need one row per [Cod Angajat] , then that should be in the GROUP BY -- and nothing else:如果每个[Cod Angajat]需要一行,那么它应该在GROUP BY ——别无他物:

SELECT [Cod Angajat], SUM([Timp declarat]
FROM [SC Vermorel SRL$ProductieVE]
WHERE CONVERT(date, Data) = @data2 AND
      ([Schimb] = '" & ProceseazaSCH(Now()) & "'
GROUP BY [Cod Angajat]
HAVING SUM([Timp declarat]) < 8;

The rest of the query simplifies as well.查询的其余部分也简化了。 There is no need to convert a date/time to a string to remove the time component.无需将日期/时间转换为字符串即可移除时间组件。 And aggregation functions don't belong in the WHERE clause.聚合函数不属于WHERE子句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM