SQL如何计算关系中每个元组的特定值?

时间:2016-03-21 22:58:39

标签: sql oracle

我在这里详细说明。

修改

我们说我的关系是r(person_name, age);

这是我想要计算的:对于关系中的每个人,我想计算与该人年龄相同的其他人的数字

我想基本上对age属性进行内部联接,我将获得具有相同年龄属性的所有person_name元组。然后我需要计算结果元组中的行数。这给了我与我计算此查询的人年龄相同的人数。 我知道如何做到这一切

我不知道如何在表格中每个人

我的结束表应该是这样的:

person_name | num_of_people_with_same_age
------------------------------------------
      A     | 3
      B     | 2
      C     | 0
            |         

这相当于常规编程语言中的双循环。我只是不知道如何用SQL术语来思考它。

1 个答案:

答案 0 :(得分:2)

Oracle安装程序

{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards  #-}

module Main where

import Control.Monad.Except

data UnlockError =
    UnlockErrorNoLogin
  | UnlockErrorNeedsSudo

data State = State {
    stateUserIsAuthenticated :: Bool
  , stateUserHasPermission :: Bool
  }

unlock :: MonadError UnlockError m => State -> m String
unlock State{..} = do
  action1
  unless stateUserIsAuthenticated
         (throwError UnlockErrorNoLogin)
  unless stateUserHasPermission
         (throwError UnlockErrorNeedsSudo)
  return "all"
  where
    action1 = return ()

main :: IO ()
main = do
  state <- conjureState
  case unlock state of
    Left UnlockErrorNoLogin ->
      p "please log in"
    Left UnlockErrorNeedsSudo ->
      p "please sudo"
    Right count ->
      p ("i love you with " ++ show count ++ " of my heart")
  where
    p =
      putStrLn
    conjureState =
      return (State True True)

<强>查询

CREATE TABLE r ( Person_name, Age ) AS
SELECT 'A', 3 FROM DUAL UNION ALL
SELECT 'B', 2 FROM DUAL UNION ALL
SELECT 'C', 1 FROM DUAL UNION ALL
SELECT 'D', 3 FROM DUAL UNION ALL
SELECT 'E', 1 FROM DUAL UNION ALL
SELECT 'F', 3 FROM DUAL UNION ALL
SELECT 'G', 4 FROM DUAL;

<强>输出

SELECT Person_Name,
       COUNT(1) OVER ( PARTITION BY Age ) AS num_people_with_same_age
FROM   r;