用条件对表格中的字段进行计数

时间:2019-03-14 14:16:08

标签: sql sql-server count

因此,我正在尝试根据类似于下表但在世界范围内有很多国家/地区的表格来计算计数。 -

Country1|Country2
   UK   | USA
   UK   | USA
   UK   | USA
   UK   | UK
   USA  | UK

我试图根据上表对每个字段进行基本计数

Country1|Country2
   1    | 1
   1    | 1
   1    | 1
   1    | 0
   1    | 1

我希望它返回-

 CountryName | Count
    UK       |  5
    USA      |  4

如上所述,这必须是动态的,并且要考虑任何国家。这些国家的名称都相同,因此美国将永远是美国,而不是美国。

谢谢!

编辑-为了更加清晰起见,我附加了查询im来返回行,

 Select 
 country1
 country2
 FROM Country1Database c1Db
 join Country2Database c2Db on c1db.MatchID = c1db.MatchID

4 个答案:

答案 0 :(得分:0)

您想要apply

select CountryName, count(*)
from table t cross apply 
     ( values (country1), (case when country2 <> country1 then country2 end) 
     ) tt(CountryName)
where CountryName is not null
group by CountryName; 

答案 1 :(得分:0)

嗯。 。 。一种方法是取消透视并计算不同的行:

select v.country, count(distinct seqnum)
from (select row_number() over (select null) as seqnum, t.*
      from t
     ) t cross apply
     (values (t.country1), (t.country2)) v(country)
group by v.country;

另一种方法是调整逻辑,以便在同一行中不对一个国家进行两次计数:j

select v.country, count(*)
from (t cross apply
     (values (t.country1)
             (case when t.country2 <> t.country1 then country2 end) 
     ) v(country)
where v.country is not null
group by v.country;

此版本应具有更好的性能。

答案 2 :(得分:0)

使用UNION ALL:

select t.country countryname, count(*) counter from (
  select country1 country from countries
  union all
  select country2 country from countries where country2 <> country1
) t
group by t.country

请参见demo

答案 3 :(得分:0)

样本数据

IF OBJECT_ID('dbo.SampleData') IS NOT NULL
DROP TABLE SampleData

CREATE TABLE SampleData (Country1 VARCHAR(20),Country2 VARCHAR(20)  )
INSERT INTO SampleData 
 SELECT 'UK'   , 'USA'  UNION ALL
 SELECT 'UK'   , 'USA'  UNION ALL
 SELECT 'UK'   , 'USA'  UNION ALL
 SELECT 'UK'   , 'UK'   UNION ALL
 SELECT 'USA'  , 'UK'

SELECT * FROM SampleData

使用UNPIVOT的Sql脚本

SELECT DISTINCT CountryName,
        COUNT(CountryData)OVER (PARTITION BY CountryName ORDER BY CountryName) AS CountryData
FROM
(
SELECT CountryName,CountryData
FROM
(
SELECT  Country1,
        Country2 
FROM SampleData
)AS SRC
UNPIVOT
(
CountryName FOR CountryData IN ([Country1],[Country2])
) AS Upvt
)dt

结果

CountryName     CountryData
----------------------------
    UK              6
    USA             4