如何子查询同一个表

时间:2018-01-05 04:37:38

标签: sql-server

我希望根据特定列中的名称创建新列。当我过滤信息时,我得到了我需要的东西,但是有很多空单元格用于不符合我要求的标准的信息。以下是我的查询和结果的示例。

我想只显示填充的单元格。因此,基本上将所有行压缩为1,并填充所有6个字段。

3 个答案:

答案 0 :(得分:1)

尝试PIVOTing行。喜欢这个

DECLARE @Activity TABLE
(
    LogonId INT,
    Activity_Date DATE,
    Activity VARCHAR(50),
    Occured DATE DEFAULT(GETDATE())
)

INSERT INTO @Activity
VALUES(1,GETDATE(),'ABC',GETDATE()),
(1,GETDATE(),'XYZ',GETDATE()-1),
(1,GETDATE(),'HIJ',GETDATE()-60)

SELECT
    *
    FROM @Activity
    PIVOT
    (
        MAX(Occured)
        FOR
        Activity IN
        (
            ABC,HIJ,XYZ
        )
    )Pvt

输入行

enter image description here

输出

enter image description here

答案 1 :(得分:1)

请使用这个简单的..不需要多个SELECT,它们会妨碍我们一次又一次地击中同一个表的性能。

SELECT logon_id,activity_date
,MIN(CASE WHEN activity = 'AsnAssignmentOnSite_evt' THEN occurred END) First_Arrival
,MAX(CASE WHEN activity = 'AsnAssignmentOnSite_evt' THEN occurred END) Last_Arrival
,MIN(CASE WHEN activity = 'OrdActivityComplete_evt' THEN occurred END) First_Completion
,MAX(CASE WHEN activity = 'OrdActivityComplete_evt' THEN occurred END) Last_Completion
,MIN(CASE WHEN activity = 'AsnAssignmentEnRoute_evt' THEN occurred END) First_Enroute
,MAX(CASE WHEN activity = 'AsnAssignmentEnRoute_evt' THEN occurred END) Last_Enroute
FROM activity
WHERE logon_id = 'e58684' AND Activity_Date = '20170127'
GROUP BY logon_id,activity_date

答案 2 :(得分:0)

像这样:

With a as (
Select min(occurred) min1, max(occured) max1
From activity
Where logon_id = 'aaa' and activity_date = '333' and activity in ('1'))
, B as (
Select min(occurred) min2, max(occured) max2
From activity
Where logon_id = 'aaa' and activity_date = '333' and activity in ('2')
)
, C as (
Select min(occurred) min3, max(occured) max3
From activity
Where logon_id = 'aaa' and activity_date = '333' and activity in ('3')
)
Select *
From a cross join b cross join c