我有以下SQL表...
Country_ID | Country |
-----------------------
1 | France |
2 | England |
3 | Germany |
4 | Scotland |
-----------------------
WorkList_ID | Places | DateOfCreation |
----------------------------------------
1 | France | 01/02/2018 |
2 | England | 11/01/2018 |
3 | Germany | 21/02/2018 |
1 | France | 13/03/2017 |
2 | England | 21/01/2018 |
4 | Scotland | 04/03/2018 |
2 | England | 08/02/2018 |
3 | Germany | 13/03/2017 |
1 | France | 09/02/2018 |
2 | England | 11/03/2017 |
---------------------------------------
使用国家/地区键来链接表格。如何生成下表:
Country | Total Count | New From Last month |
--------------------------|----------------------
France | 3 | 1 |
England | 4 | 2 |
Germany | 2 | 1 |
Scotland | 1 | 0 |
--------------------------------------------------
我想显示工作清单的总数以及上个月添加的所有新工作清单?
这是我到目前为止所做的:
(SELECT Places, COUNT(Places) as 'Outstanding List'
FROM WorkList
WHERE Places IN
(SELECT Country FROM tblCountry)
GROUP BY Places)
答案 0 :(得分:1)
SELECT COUNTRY,
TOT.TOTAL [TOTAL COUNT],
LAST.TOTAL [NEW FROM LAST MONTH]
FROM tblCountry T
LEFT JOIN
(SELECT Places, COUNT(Places) TOTAL
FROM WorkList W
INNER JOIN tblCountry C ON C.Country = W.Places
WHERE W.DateOfCreation BETWEEN DATEADD(MONTH, -1, GETDATE()) AND GETDATE()
GROUP BY Places) TOT ON TOT.PLACES = T.COUNTRY
LEFT JOIN
(SELECT Places, COUNT(Places) TOTAL
FROM WorkList W
INNER JOIN tblCountry C ON C.Country = W.Places
GROUP BY Places) LAST ON LAST.PLACES = T.COUNTRY
答案 1 :(得分:1)
我使用了左连接,以防你有一些国家还没有任何新的国家。这样,即使没有订单,您也会列出所有列出的国家/地区。
SELECT Country, NVL(pt.total_count,0), NVL(nt.new_count,0)
FROM country_table cl
LEFT JOIN (SELECT worklist _id,
count(worklist_id) as total_count
FROM places_table
GROUP BY worklist_id) pt ON pt.worklist_id = cl.country_id
LEFT JOIN (SELECT worklist _id,
count(worklist_id) as new_count
FROM places_table
WHERE dataofcreate > yourdate
GROUP BY worklist_id) nt ON nt.worklist_id = cl.country_id
答案 2 :(得分:1)
这应该可以胜任。只是一个简单的LEFT JOIN
,您可以在上个月使用CASE
表达式:
USE Sandbox;
GO
CREATE TABLE #Country (Country_ID int, Country varchar(10));
INSERT INTO #Country
VALUES (1,'France'),
(2,'England'),
(3,'Germany'),
(4,'Scotland');
CREATE TABLE #Worklist (WorkList_ID int, Places varchar(10), DateOfCreation date);
INSERT INTO #Worklist
SELECT Id, Place, CONVERT(date, Creation,103)
FROM (VALUES (1,'France','01/02/2018'),
(2,'England','11/01/2018'),
(3,'Germany','21/02/2018'),
(1,'France','13/03/2017'),
(2,'England','21/01/2018'),
(4,'Scotland','04/03/2018'),
(2,'England','08/02/2018'),
(3,'Germany','13/03/2017'),
(1,'France','09/02/2018'),
(2,'England','11/03/2017')) WL(ID, Place, Creation);
GO
SELECT C.Country,
COUNT(WL.WorkList_ID) AS Total,
COUNT(CASE WHEN DateOfCreation >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1,0) AND DateOfCreation < DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()),0) THEN WL.WorkList_ID END) AS LastMonth
FROM #Country C
LEFT JOIN #Worklist WL ON C.Country = WL.Places
GROUP BY C.Country
GO
DROP TABLE #Country;
DROP TABLE #Worklist;