[英]How to create new columns with count values based on the values from another column SQL
I am using Big Query and my table looks like this: 我正在使用Big Query,我的表格如下所示:
ID Month Values
ID月值
1234 Aug P
1234年8月
1234 Sept P1234年9月
3456 Aug D3456年8月4日
3456 Sept DD 3456年9月
4567 Aug P4567年8月
4567 Sept DD 4956年9月
I want to generate new column for each month and ID containing P,D as column names and values is their count for each ID and Month. 我想为每个月和包含P,D的ID生成一个新列,列名称和值是每个ID和Month的计数。 Like below:
如下所示:
ID Month PD
ID月PD
1234 Aug 1 01234八月1 0
1234 Sept 1 01234年9月1日0
3456 Aug 0 13456八月0 1
3456 Sept 0 13456 9月0 1
4567 Aug 1 04567八月1 0
4567 Sept 1 14567 9月1日1
Below is for BigQuery Standard SQL 以下是BigQuery标准SQL
#standardSQL
SELECT id, month, IF(value='P', 1, 0) AS p, IF(value='D', 1, 0) AS d
FROM `project.dataset.table`
you can play with above using dummy data from your question 您可以使用问题中的虚拟数据进行上述操作
#standardSQL
WITH `project.dataset.table` AS (
SELECT 1234 id, 'Aug' month, 'P' value UNION ALL
SELECT 1234, 'Sept', 'P' UNION ALL
SELECT 3456, 'Aug', 'D' UNION ALL
SELECT 3456, 'Sept', 'D' UNION ALL
SELECT 4567, 'Aug', 'P' UNION ALL
SELECT 4567, 'Sept', 'D'
)
SELECT id, month, IF(value='P', 1, 0) AS p, IF(value='D', 1, 0) AS d
FROM `project.dataset.table`
-- ORDER BY id
with result 结果
Row id month p d
1 1234 Aug 1 0
2 1234 Sept 1 0
3 3456 Aug 0 1
4 3456 Sept 0 1
5 4567 Aug 1 0
6 4567 Sept 0 1
In case if you have duplicate rows in your table and need to count values vs. just presenting them (as it is in above query) you can use below example 如果您的表中有重复的行并且需要计算值而不是仅仅显示它们(如上面的查询中所示),则可以使用以下示例
#standardSQL
WITH `project.dataset.table` AS (
SELECT 1234 id, 'Aug' month, 'P' value UNION ALL
SELECT 1234, 'Sept', 'P' UNION ALL
SELECT 1234, 'Sept', 'P' UNION ALL
SELECT 3456, 'Aug', 'D' UNION ALL
SELECT 3456, 'Sept', 'D' UNION ALL
SELECT 4567, 'Aug', 'P' UNION ALL
SELECT 4567, 'Sept', 'D'
)
SELECT id, month, COUNTIF(value='P') AS p, COUNTIF(value='D') AS d
FROM `project.dataset.table`
GROUP BY id, month
-- ORDER BY id, month
with result 结果
Row id month p d
1 1234 Aug 1 0
2 1234 Sept 2 0
3 3456 Aug 0 1
4 3456 Sept 0 1
5 4567 Aug 1 0
6 4567 Sept 0 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.