我有两张表如下
companyid name
1 pwc
2 dell
3 microsoft
4 google
5 yahoo
6 twitter
companyid state month powerconsumption
1 newyork jan 240
2 california jan 130
3 arizona jan 210
4 texas jan 130
5 texas jan 650
6 california jan 310
2 arizona jan 340
我想查询列出每个州的公司,这个州在1月份消耗了最大的权力。所以上述数据的结果将是
arizona dell 340
california twitter 310
newyork pwc 240
texas yahoo 650
答案 0 :(得分:0)
SELECT DISTINCT(SELECT name FROM company WHERE(companyid =(SELECT TOP(1)companyid FROM consumption WHERE(state = a.state)AND(month = a.month)ORDER BY powerconsumption DESC)))AS公司, 州, 月, (SELECT TOP(1)powerconsumption FROM consumption AS consumption_1 WHERE(state = a.state)AND(month = a.month)ORDER BY powerconsumption DESC)AS powerconsumption 来自dbo.consumption AS a
答案 1 :(得分:0)
尝试此查询:
SELECT x.State,
c.Name AS CompanyName,
x.PowerConsumption
FROM
(
SELECT pc.CompanyID, pc.State, pc.PowerConsumption,
DENSE_RANK() OVER(PARTITION BY pc.State ORDER BY pc.PowerConsumption DESC) AS Rnk
FROM dbo.PowerConsumptionTable pc
WHERE pc.Month = 'jan'
) x INNER JOIN dbo.CompanyTable c ON x.CompanyID = c.CompanyID
WHERE x.Rnk = 1
答案 2 :(得分:0)
我得到了答案,这对我来说似乎是最好的方式。它有一个子查询,但我没有办法避免这种情况。
选择t2.state,t1.name,t2.powerconsumption FROM table1 t1 JOIN table2 t2 ON t1.companyid = t2.companyid 其中t2.powerconsumption =(从table2 t3中选择MAX(t3.powerconsumption),其中t3.state = t2.state和t3.month ='jan')
<强> SQL Fiddle 强>