2016-05-11 8 views
0
SELECT Count(*) AS MonthTotal 
FROM CRMProjects 
WHERE CreatedDate between '01 May 2016' and '31 May 2016' 

SELECT Count(*) AS YearTotal 
FROM CRMProjects 
WHERE CreatedDate between '01 Jan 2016' and '31 Dec 2016' 

SELECT Count(*) AS MonthNew 
FROM CRMProjects 
WHERE CreatedDate between '01 May 2016' and '31 May 2016' 
AND SystemType = 'O' 

SELECT Count(*) AS YearClosed 
FROM CRMProjects 
WHERE CreatedDate between '01 Jan 2016' and '31 Dec 2016' 
AND SystemType = 'C' 

テーブル内の月のみが入力されますが、Visual Studioでは1つのデータセットに対して複数のSELECT文を使用できないため、他のセクションにはデータが入力されません。SQLでselect文を1つ作ることはできますか?

答えて

0

私はこのような何かを示唆している:

SELECT 'Month Total' AS Label, Count(*) AS Value 
FROM CRMProjects 
WHERE CreatedDate between '01 May 2016' and '31 May 2016' 

UNION ALL 

SELECT 'Year Total' AS Label, Count(*) AS Value 
FROM CRMProjects 
WHERE CreatedDate between '01 Jan 2016' and '31 Dec 2016' 

UNION ALL 

SELECT 'Month New' AS Label, Count(*) AS Value 
FROM CRMProjects 
WHERE CreatedDate between '01 May 2016' and '31 May 2016' 
AND SystemType = 'O' 

UNION ALL 

SELECT 'Year Closed' AS Label, Count(*) AS Value 
FROM CRMProjects 
WHERE CreatedDate between '01 Jan 2016' and '31 Dec 2016' 
AND SystemType = 'C' 
0

あなたはこのためSUMIFの一種としてSUM(CASE)を使用することができます...

SELECT 
    SUM(CASE WHEN CreatedDate between '01 May 2016' and '31 May 2016' THEN 1 END) AS MonthTotal, 
    SUM(1) AS YearTotal, 
    SUM(CASE WHEN CreatedDate between '01 May 2016' and '31 May 2016' AND SystemType = 'O' THEN 1 END) AS MonthNew, 
    SUM(CASE WHEN SystemType = 'C' THEN 1 END) AS YearClosed 
FROM 
    CRMProjects 
WHERE 
    CreatedDate between '01 Jan 2016' and '31 Dec 2016' 

これは、あなただけの関連するセクションをスキャンすることを保証しますテーブルを1回抽出し、結果を1回の集計で集計します。

0

、独自の列として各カウントを選択します。

Select 
    (SELECT Count(*) 
     FROM CRMProjects 
     WHERE CreatedDate between '01 May 2016' and '31 May 2016') AS MonthTotal, 


    (SELECT Count(*) 
     FROM CRMProjects 
     WHERE CreatedDate between '01 Jan 2016' and '31 Dec 2016') AS YearTotal, 


    (SELECT Count(*) 
     FROM CRMProjects 
     WHERE CreatedDate between '01 May 2016' and '31 May 2016' 
     AND SystemType = 'O') AS MonthNew, 


    (SELECT Count(*) 
     FROM CRMProjects 
     WHERE CreatedDate between '01 Jan 2016' and '31 Dec 2016' 
     AND SystemType = 'C') AS YearClosed 
関連する問題