我遇到了一些麻煩,下面是代碼,我嘗試從兩個不同的表中獲取計數,然後按日期對它們進行分組。SQL Group by Totals issue
declare @fromdate as date
declare @todate as date
set @fromdate = CONVERT(date,GETDATE()-3,101)
set @todate = CONVERT(date,GETDATE(),101)
USE database
SELECT
CONVERT(date,created_date,101) as OrdDate,
col1= (SELECT COUNT(distinct cust_id)
FROM table1
WHERE created_date BETWEEN @fromdate and @todate),
col2= (SELECT COUNT(distinct cust_id)
FROM table1
WHERE [status] LIKE 'P%' and created_date BETWEEN @fromdate and @todate),
col3= (SELECT COUNT(distinct cust_id)
FROM table2
WHERE created_date BETWEEN @fromdate and @todate),
col4= (SELECT COUNT(distinct cust_id)
FROM table2
WHERE created_date between @fromdate and @todate and result_error like 'FAIL%')
FROM table1
WHERE created_date BETWEEN @fromdate and @todate
GROUP BY CONVERT(date,created_date,101)
ORDER BY CONVERT(date,created_date,101)
它在一起計算所有的日子,我試着給每個表達式添加Group,但是沒有去。有什麼建議麼?
OrdDate col1 col2 col3 col4
2011-12-19 5000 4000 3000 2000
2011-12-20 5000 4000 3000 2000
2011-12-21 5000 4000 3000 2000
我要的是這樣的事情
OrdDate col1 col2 col3 col4
2011-12-19 1500 1500 500 750
2011-12-20 2500 750 1000 1000
2011-12-21 1000 1750 1500 250
如果您通過刪除結果是什麼組? –
如果你在一張桌子上沒有2011-12-20怎麼辦?一般來說,除非你想要一行,否則不要做這種不相交的聚集。 – gbn
這個查詢中實際上有三個表 - table1,customer_order和table2。 –