基于选择不同列中的最高序列(Account_Occupant),我正在努力查询数据,我只需要一行表中的一行(数千个)。
我需要返回一个不同的帐号(90006),最高的account_occupant(11)和与该account_occupant(MICHAEL)对应的名称。以下是数据样本:
DSPDoubleSplitComplex
我需要返回的一个例子是:
Account_NUM Account_Occupant Name
90006 1 JOHN
90006 2 MARY
90006 3 MARY
90006 4 KERRI
90006 5 PATRICIA
90006 6 DARYL
90006 7 ASHLEY
90006 8 DARYL
90006 9 DIANE
90006 10 DARYL
90006 11 MICHAEL
这是最近的查询尝试:
Account_NUM Account_Occupant Name
90006 11 MICHAEL
我已经做了大量的搜索和尝试各种变体的分组依据,在我在这个论坛中找到的where语句,子选择和联合语句中分组,但仍然没有做到正确。编辑道歉要求人们提出问题,指出我提问中的错误 - 非常感谢。
答案 0 :(得分:1)
如果我正确理解您的描述,您就不需要分组。一个简单的降序将给你想要的东西:
SELECT TOP 1 Account_NUM, Account_Occupant, Name
FROM table1
ORDER BY Account_Occupant DESC
如果您的数据库中有其他记录,而Account_NUM
中的90006
不是Account_NUM
,而您只想要SELECT TOP 1 Account_NUM, Account_Occupant, Name
FROM table1
WHERE Account_NUM = 90006
ORDER BY Account_Occupant DESC
,那么只需添加一个条件:
var xAxis = d3.axisBottom(x)
.tickValues(x.domain().filter(function(d, i) {return !(i%4);}));
答案 1 :(得分:1)
如果您正在寻找前1 PER Account_Num ,那么这只是另一种选择。
我提交此内容只是因为您正在寻找GROUP BY和JOINs
Select Top 1 with ties *
From YourTable
Order By Row_Number() over (Partition By Account_NUM Order By Account_Occupant Desc)
答案 2 :(得分:1)
您可以尝试另一种方法。
CREATE TABLE TBL(Account_NUM VARCHAR(100),Account_Occupant INT,Name VARCHAR(100))
INSERT INTO TBL
SELECT '123',11,'ABC'
INSERT INTO TBL
SELECT '123',12,'XYZ'
INSERT INTO TBL
SELECT '124',11,'ABC'
INSERT INTO TBL
SELECT '124',12,'XYZ'
SELECT DISTINCT T.*, T1.Name FROM
(
SELECT Account_NUM, MAX(Account_Occupant) OVER (PARTITION BY Account_NUM) AS MAX_Account_Occupant
FROM TBL
) T
INNER JOIN TBL T1 ON T1.Account_NUM= T.Account_NUM AND T1.Account_Occupant=T.MAX_Account_Occupant
输出
Account_NUM MAX_Account_Occupant Name
------------ -------------------- -----
123 12 XYZ
124 12 XYZ