使用SQL将记录放在一行中

时间:2016-01-27 16:50:01

标签: sql

如何在SQL查询中将两条记录合并为一行? 我的数据如下:

Name    | P_Address   | M_Address
---------------------------------------
Smith   | 123 Main St | PO Box 123

我需要得到一个如下所示的结果:

import math
import numpy as np

scores = [3.0, 1.0, 0.2]
y = [0,0,0]
i = 0
j = 0
k = 0
sum = 0

def myFunc(x):
    global sum
    global i
    global j

    if not y:
        for s in scores:
            y[i] = 0.5 * scores[i] + 0.2
            i = i+1

    if sum == 0:
        for s2 in scores:
            sum = sum + math.exp(y[j])
            j = j+1

    print sum    
    return math.exp(x)/sum

for s3 in scores:
    print(myFunc(scores[k]))
    k = k+1

2 个答案:

答案 0 :(得分:3)

使用conditional Aggregate执行此操作

select Name,
       Max(case when Address_Type = 'P' then Address End) as P_Address,
       Max(case when Address_Type = 'M' then Address End) as M_Address
From Yourtable
Group by Name

答案 1 :(得分:0)

如果您知道每个人总是只有一个“P”地址且从不超过一个“M”地址,那么以下内容将起作用:

SELECT
    P.name,
    P.address AS p_address,
    M.address AS m_address
FROM
    My_Table P
LEFT OUTER JOIN My_Table M ON
    M.name = P.name AND
    M.address_type = 'M'
WHERE
    P.address_type = 'P'

如果是这种情况,那么我还要确保通过数据库约束强制执行这些业务规则。