SQL:尝试将一系列" count" s结果放入表中

时间:2014-07-08 17:57:15

标签: sql select count

我必须做一系列的'计数'用SQL来弄清楚吸毒情况。我是SQL / SAS的新手,但我编写了以下简单的(和可怕的宏):

        %macro rxs (title, data, zz);
        Title &title &zz;
        proc sql; 
            select count (studyid) as NumberofRxs from &data where zz=&zz; 
            select count (distinct studyid) as NUMofPATIENTS from &data where zz=&zz; 
            select count (studyid) as numRXswithSTATIN from &data where zz=&zz and exposed=1; 
            select count (distinct studyid) as numPATIENTSwithdrug from &data where zz=&zz and exposed=1;
            select count (studyid) as numRXSnodrug from &data where zz=&zz and exppsed=0;
            select count (distinct studyid) as numPATIENTSSnodrug from &data where zz=&zz and exposed=0;
                quit; %mend rxs;

结果很好......它只是有点乱。如果我可以将它们转储到一个简单的表中,那就太好了。就像我说的,我是新手,所以解决方案可能非常简单。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您可以将它们组合成以下内容,而不是拥有所有这些不同的选择:

select  count (studyid) as NumberofRxs,
        count (distinct studyid) as NUMofPATIENTS,
        count (Case when exposed = 1 Then studyid Else null End) as numRXswithSTATIN,
        count (distinct Case when exposed = 1 Then studyid Else null End) as numPATIENTSwithdrug,
        count (Case when exposed = 0 Then studyid Else null End) as numRXSnodrug,
        count (distinct Case when exposed = 0 Then studyid Else null End) as numPATIENTSSnodrug

from &data where zz=&zz; 

请注意我在某些计数中有一个案例陈述。 Count忽略null的值。由于您只想基于公开计算studyid,因此如果公开的值是错误的,则case语句将返回null。然后伯爵会忽略它。