我有一个简单的问题。如何在一个查询中选择我需要的两个值?目前我正在做这个,它工作正常,但显然会运行两个查询,当一个人应该这样做。我尝试了MAX(columnA)和GROUP BY ColumnB,但是返回了多行。我只想要返回一行。
DECLARE @biID bigint
, @dtThreshold DateTime
SELECT @biID = MAX(biID)
FROM tbPricingCalculationCount WITH (NOLOCK)
SELECT @dtThreshold = dtDateTime
FROM tbPricingCalculationCount WITH (NOLOCK)
WHERE biID = @biID
我希望在一个查询中正确设置这两个变量。我怎样才能做到这一点?
谢谢, 〜CK
答案 0 :(得分:8)
你能不能这样做吗?
SELECT TOP 1 @biID = biID, @dtThreshold = dtDateTime
FROM tbPricingCalculationCount WITH (NOLOCK)
ORDER BY biID DESC;
答案 1 :(得分:1)
怎么样
SELECT TOP 1 @biID = biID, @dtThreshold = dtDateTime
FROM tbPricingCalculationCount (NOLOCK)
ORDER BY biID desc
答案 2 :(得分:1)
这将返回具有最大biID的行的dtDateTime:
SELECT t1.dtDateTime
FROM tbPricingCalculationCount t1
LEFT JOIN tbPricingCalculationCount t2
ON t2.biID > t1.biID
WHERE t2.biID IS NULL
如果多个行共享相同的“最大”biID,则需要使用TOP将结果限制为1:
SELECT TOP 1 t1.dtDateTime
FROM tbPricingCalculationCount t1
LEFT JOIN tbPricingCalculationCount t2
ON t2.biID > t1.biID
WHERE t2.biID IS NULL
答案 3 :(得分:1)
怎么样:
DECLARE
@biID bigint,
@dtThreshold DateTime
SELECT
@dtThreshold = A.dtDateTime,
@biID = B.biID
FROM tbPricingCalculationCount A
INNER JOIN (SELECT MAX(biID) biID
FROM tbPricingCalculationCount) B
ON A.biID = B.biID
如果您没有在其他地方使用biID,您甚至可以将其修剪为:
DECLARE
@dtThreshold DateTime
SELECT
@dtThreshold = A.dtDateTime
FROM tbPricingCalculationCount A
INNER JOIN (SELECT MAX(biID) biID
FROM tbPricingCalculationCount) B
ON A.biID = B.biID