我正在学习一些基本的 SQL 查询技能,并处理日期。我成功获得了以下内容。
SELECT
[FirstName],
[LastName],
[JobTitle],
[JoiningDate]
DATEDIFF(day, StartDate, '2021/03/20') AS DateDifference
FROM
[GenericITCompany].[dbo].[Employees]
WHERE
JobTitle = 'UnityDeveloper';
这将返回 Unity 团队的每位开发人员在公司工作的天数。
现在,我想知道谁在公司待的时间最长。
我试过了:
SELECT
[FirstName],
[LastName],
[JobTitle],
[JoiningDate]
DATEDIFF(day, StartDate, '2021/03/20') AS DateDifference
MAX(DateDifference) AS LongestServingEmployee
FROM
[GenericITCompany].[dbo].[Employees]
WHERE
JobTitle = 'UnityDeveloper';
那是行不通的。我可能遗漏了一些非常明显的东西。
注1:我了解Max的基本用法。例如,
SELECT
MAX(StartDate) AS MaximumStartDate
FROM
[GenericITCompany].[dbo].[Employees]
但是,我主要面临将 MAX 应用于查询生成表的挑战。我相信这是我的主要问题。
注2:我查看了一些存在类似问题的现有问题
Fetch the row which has the Max value for a column
How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?
但我无法从他们那里理解。
答案 0 :(得分:1)
您可以像以下子查询一样使用 MIN 函数来获取最小日期而不是日期差异。
SELECT
[FirstName],
[LastName],
[JobTitle],
[JoiningDate]
DATEDIFF(day, StartDate, '2021/03/20') AS DateDifference
FROM [GenericITCompany].[dbo].[Employees]
WHERE JobTitle='UnityDeveloper'
-- Getting the smallest StartDate
AND StartDate = (
SELECT MIN(StartDate) AS MaximumStartDate
FROM [GenericITCompany].[dbo].[Employees]
)
答案 1 :(得分:1)
不能在同一个查询中使用 DateDifference
列名
SELECT
[FirstName],
[LastName],
[JobTitle],
[JoiningDate],
DATEDIFF(day, StartDate, '2021/03/20') AS DateDifference
INTO #Employees
FROM [GenericITCompany].[dbo].[Employees]
WHERE JobTitle='UnityDeveloper';
Select *
From #Employees where DateDiffernce = (Select Max(DateDiffernce) From #Employees)
答案 2 :(得分:1)
我不清楚您希望看到的结果是什么,您是否只想看到服务日期最长的员工(可能有关系?)
或者每行天数最多的所有员工 - 这似乎是您的查询试图执行的操作,在这种情况下,您可以执行以下操作,并按 LongestServiceEmployee 排序。我还用 from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.vgg16 import VGG16, preprocess_input
from tensorflow.keras.models import Model
import numpy as np
from PIL import Image
#from feature_extractor import FeatureExtractor
from datetime import datetime
from flask import Flask, request, render_template
from pathlib import Path
from keras.optimizers import Adam
from tensorflow.keras.layers import Dropout, Dense, Activation, Flatten
class FeatureExtractor:
def __init__(self):
input_shape = (224, 224, 3)
base_model = VGG16(weights='imagenet', include_top=False, input_shape=input_shape)
for layer in base_model.layers:
layer.trainable = False
last = base_model.layers[-1].output
x = Flatten()(last)
x = Dense(1000, activation='relu', name='fc1')(x)
x = Dropout(0.3)(x)
x = Dense(10, activation='softmax', name='predictions')(x)
model = Model(base_model.input, x)
model.compile(optimizer=Adam(lr=0.001),
loss = 'categorical_crossentropy',metrics=['accuracy'])
self.model = Model(inputs=base_model.input, outputs=base_model.layers[-1].output)
def extract(self, img):
"""
Extract a deep feature from an input image
Args:
img: from PIL.Image.open(path) or tensorflow.keras.preprocessing.image.load_img(path)
Returns:
feature (np.ndarray): deep feature with the shape=(4096, )
"""
img = img.resize((224, 224)) # VGG must take a 224x224 img as an input
img = img.convert('RGB') # Make sure img is color
x = image.img_to_array(img) # To np.array. Height x Width x Channel. dtype=float32
x = np.expand_dims(x, axis=0) # (H, W, C)->(1, H, W, C), where the first elem is the number of img
x = preprocess_input(x) # Subtracting avg values for each pixel
feature = self.model.predict(x)[0] # (1, 4096) -> (4096, )
return feature / np.linalg.norm(feature) # Normalize
path = "/home/virtuag/www/storage/searchSCB.jpg"
img = Image.open(path)
app = Flask(__name__)
fe = FeatureExtractor()
features = []
img_paths = []
for feature_path in Path("/home/virtuag/www/storage/images_article").glob("*.npy"):
features.append(np.load(feature_path))
img_paths.append(Path("/home/virtuag/www/storage/images_article") / (feature_path.stem + ".jpg"))
features = np.array(features)
query = fe.extract(img)
dists = np.linalg.norm(features-query, axis=1)
ids = np.argsort(dists)[:30]
scores = [img_paths[id] for id in ids]
代替了您的硬编码日期
GETDATE()
如果您只想找到具有最大值的员工,则将查询包装在外部 SELECT
[FirstName],
[LastName],
[JobTitle],
[JoiningDate]
DATEDIFF(day, createdate, GETDATE()) AS DateDifference
MAX(day, createdate, GETDATE()) over() AS LongestServingEmployee
FROM [dbo].[Employees]
WHERE JobTitle = 'UnityDeveloper'
order by LongestServingEmployee desc;
中并进行过滤:
select