计算一个计算字段

时间:2017-02-21 01:02:23

标签: tsql sql-server-2012

使用SQL Server 2012。

我有以下代码:

def main():
    enter code herescores = input("Enter five test scores seperated by commas:")
    listScores = scores.split(",")`enter code here`
    determine_grade(listScores)
    calc_average(listScores)

def determine_grade(grades):
    for num in grades:
        if int(num) >= 90 and int(num) <= 100:
            print("A")
        elif int(num) >=80 and int(num) <= 89:
            print("B")
        elif int(num) >=70 and int(num) <= 79:
            print("C")
        elif int(num) >=60 and int(num) <= 69:
            print("D")
        else:
            print("F")


def calc_average(grades):
    total = 0
    for num in grades:
        total += int(num)
    average = total / 5
    print(average)


#def show_letters(values):
main()

我需要编辑此查询,以便为每个Select Distinct [A_number] + '-' + convert(varchar(10),[zone]) As myNumber FROM [dbo].[soils]; 计算一次。 的问候,

3 个答案:

答案 0 :(得分:1)

我要做的是使用group by声明:

SELECT A_number,
    zone,
    COUNT(*) AS c
FROM dbo.soils
GROUP BY A_number,
    zone;

然后,使用该结果来连接字段。这样做将允许使用索引:

WITH numbers AS (
   SELECT A_number,
        zone,
        COUNT(*) AS c
    FROM dbo.soils
    GROUP BY A_number,
        zone
)
SELECT A_number + '-' + convert(varchar(10),zone) As myNumber,
    c AS number_count
FROM numbers;

答案 1 :(得分:0)

使用COUNT()

SELECT COUNT(DISTINCT [A_number]  + '-' + CONVERT(VARCHAR(10),[zone]))
FROM [dbo].[soils]

这将为您提供转化中唯一myNumber的统计数据。

如果您需要计算每个唯一的mynumber,请考虑GROUP BY

SELECT [A_number]  + '-' + CONVERT(VARCHAR(10),[zone]), COUNT(*)
FROM [dbo].[soils]
GROUP BY [A_number]  + '-' + CONVERT(VARCHAR(10),[zone])

答案 2 :(得分:0)

要获取与myNumber的每个值相关联的行数,请丢弃DISTINCT并改为使用GROUP BY

最简单的例子,在GROUP BY子句的SELECT列表中重复表达式:

SELECT [A_number] + '-' + CONVERT(VARCHAR(10),[zone]) AS myNumber
     , COUNT(*) AS cnt
  FROM [dbo].[soils]
 GROUP
    BY [A_number] + '-' + CONVERT(VARCHAR(10),[zone])

对于琐碎的集合,性能不会成为问题。对于较大的套装,性能会受到影响。解决方案是重新编写查询以利用现有索引,或添加适当的索引。