单个表中的多个SQL查询

时间:2016-11-04 09:53:18

标签: sql sql-server tsql

我是SQL的新手,我希望有人帮助我。 我有两个查询,我想在两个不同的列中放在同一个表中(如果可能的话)。

示例数据:

def construct_query(form):
    query = db.session.query(*[field.label.text for field in form if field.data and field.name != 'csrf_token'])
    if form.search_by_album.data:
        query = query.filter(Album.title == form.search_by_album.data)
    if form.search_by_artist.data:
        query = query.filter(Artist.name == form.search_by_artist.data)
    if form.search_track.data:
        query = query.filter(Track.title == form.search_track.data)
    if form.year.data:
        query = query.filter(Album.year == form.year.data)
    result = query.all()
    return result

预期结果:

BP Name     Disbursment Date
A           2013          
B           2013
C           2015
A           2015 
B           2016
D           2015
D           2016
E           2015
E           2016
F           2016
G           2016

首次查询(“实际年份”栏目

BP Name 2016          BP Name 2015
F                      C
G                      D
                       E

第二个查询(将是“上一年”列)

SELECT DISTINCT t."BP Name"
FROM (  SELECT
             "BP Name",
             "Disbursment Date"
    FROM  "SB_MD" 
    WHERE    year("Disbursment Date")  = Year(getdate())
) t LEFT JOIN(  SELECT "BP Name"
    FROM  "SB_MD" 
    WHERE    year("Disbursment Date")  < year(getdate())
) t1 ON t."BP Name"  = t1."BP Name"  
WHERE    t1."BP Name"  is null

1 个答案:

答案 0 :(得分:0)

您可以使用完整外部联接来解决您的问题,如下所示:

SELECT A1.[BP Name] AS 'BP NAME 2016',B1.[BP Name] AS 'BP NAME 2015'
FROM
(
    SELECT 
        ROW_NUMBER() OVER(ORDER BY [BP Name] ASC) AS Row#, [BP Name]
    FROM
    (
        SELECT DISTINCT t."BP Name"
        FROM (  SELECT
                 "BP Name",
                 "Disbursment Date"
                    FROM  "SB_MD" 
            WHERE    year("Disbursment Date")  = Year(getdate()
        )) t 
        LEFT JOIN(  SELECT "BP Name"
            FROM  "SB_MD" 
            WHERE    year("Disbursment Date")  < year(getdate())
        ) t1 ON t."BP Name"  = t1."BP Name"  
        WHERE    t1."BP Name"  is null
    ) A
) A1
FULL OUTER JOIN
(
    SELECT 
        ROW_NUMBER() OVER(ORDER BY [BP Name] ASC) AS Row#, [BP Name]
    FROM
    (
        SELECT DISTINCT t."BP Name"
        FROM (  SELECT
             "BP Name",
             "Disbursment Date"
            FROM  "SB_MD" 
            WHERE    year("Disbursment Date")  = (Year(getdate()) -1)) t 
        LEFT JOIN(  SELECT "BP Name"
            FROM  "SB_MD" 
            WHERE    year("Disbursment Date")  < (year(getdate()) -1)
            ) t1 ON t."BP Name"  = t1."BP Name"  
        WHERE    t1."BP Name"  is null
    ) B
) B1 ON A1.ROW# = B1.ROW#