I have the following table on MS-SQL Server 2005.
CREATE TABLE tblData ( ID int NOT NULL PRIMARY KEY, FOOBAR1 bit, LOCATION varchar(50) ) GO INSERT INTO tblData (ID, FOOBAR1, LOCATION) VALUES (1,'True','Paris') GO INSERT INTO tblData (ID, FOOBAR1, LOCATION) VALUES (2,'True','New York') GO INSERT INTO tblData (ID, FOOBAR1, LOCATION) VALUES (3,'False','Paris') GO INSERT INTO tblData (ID, FOOBAR1, LOCATION) VALUES (4,'False',NULL) GO INSERT INTO tblData (ID, FOOBAR1, LOCATION) VALUES (5,NULL,'Paris') GO
tblCities looks like this:
CREATE TABLE tblCities ( cityName varchar(50) ) GO INSERT INTO tblCities (cityName) VALUES ('Paris') GO INSERT INTO tblCities (cityName) VALUES ('New York') GO INSERT INTO tblCities (cityName) VALUES ('London')
I want to have aggregates for the bit FOOBAR1 (True, False and NULL) So this is the SELECT statement that I've tried:
SELECT UPPER(tblCities.cityName) AS City ,SUM (CASE WHEN tblData.FOOBAR1 = 1 THEN 1 ELSE 0 END) AS Yes ,SUM (CASE WHEN tblData.FOOBAR1 = 0 THEN 1 ELSE 0 END) AS [No] ,SUM (CASE WHEN tblData.FOOBAR1 IS NULL THEN 1 ELSE 0 END) AS NoData FROM tblCities LEFT JOIN tblData ON tblCities.cityName = tblData.LOCATION GROUP BY tblCities.cityName
Results are the following:
City | Yes | No | NoData | LONDON | 0 | 0 | 1 | NEW YORK | 1 | 0 | 0 | PARIS | 1 | 1 | 1 |
Ideally, I want all five records in tblData to be accounted for in the SELECT statement:
City | Yes | No | NoData | LONDON | 0 | 0 | 0 | NEW YORK | 1 | 0 | 0 | PARIS | 1 | 1 | 1 | NO DATA | 0 | 1 | 0 |
Thoughts?
Aucun commentaire:
Enregistrer un commentaire