复杂的SQL Server SELECT查询

时间:2011-12-13 20:18:18

标签: sql sql-server

我希望获得每周工作时间少于每家店铺平均工作时间的工人名单。

工:

  • 名称
  • 小时(一个工人每周工作一小时)
  • 商店(工人工作的商店)

这给了我一对(商店,商店的平均营业时间)列表:

SELECT shop, AVG(hours) AS 'av' FROM Workers GROUP BY shop

这是我的' Pseudo SQL':

SELECT 
    name, hours, 
    (SELECT shop, AVG(hours) AS 'av' FROM Workers GROUP BY shop).av 
FROM Workers 
WHERE 
   (SELECT shop, AVG(hours) AS 'av' FROM Workers GROUP BY shop).av > Workers.hours 
   AND (SELECT shop, AVG(hours) AS 'av' FROM Workers GROUP BY shop).shop = Workers.shop

我需要在单个T-SQL查询中完成此操作。你能救我吗?

3 个答案:

答案 0 :(得分:3)

您可以使用Common Table Expressions

With averageHours as (SELECT shop, AVG(hours) AS 'av' FROM Workers GROUP BY shop)
SELECT name, hours, averageHours.av
FROM Workers WHERE averageHours.av > Workers.hours 
             AND averageHours.shop = Workers.shop

答案 1 :(得分:2)

你非常接近。我完全不了解你的查询(什么是“Pracownicy”表?),但这应该给你一个想法(未经测试的查询):

SELECT w.name,
       w.hours,
       w.shop,
       avg.average
  FROM Workers AS w,
       (SELECT shop,
               AVG(hours) AS average
          FROM Workers
        GROUP BY shop) AS avg
 WHERE w.shop = avg.shop
   AND w.hours < avg.average

请注意这里的技巧:使用查询作为FROM子句中的表。这允许您减少重复子选择的数量。

答案 2 :(得分:-1)

SELECT NAME FROM TABLE T1 WHERE T1.HOUR < ( SELECT AVG(HOUR) FROM TABLE GROUP BY T1.NAME )

这是最简单的查询,无任何混乱。