繁体   English   中英

如何使用 SQLite 将值转入列中?

[英]How do I pivot values into columns with SQLite?

我用以下代码制作了一个名为tbl的表:

CREATE TABLE tbl
    (
      `Year` int, 
      `Album` varchar(255),
      `Artist` varchar(255),
      `Label` varchar(255),
      `Genre` varchar(255),
      `id` int
    )
;

INSERT INTO tbl
    (
      `Year`,
      `Album`,
      `Artist`,
      `Label`,
      `Genre`,
      `id`
    )
VALUES
    (1990, "Greatest Hits", "The Best", "Least Def", "hip hop", 123),
    (1990, "Greatest Hits", "The Best", "Roofless", "hip hop", 123),
    (1990, "4-Boyz", "3 Guyz", "Pacific", "pop-dance", 23),
    (1990, "4-Boyz", "3 Guyz", "Atlantic", "pop-dance", 23)
;

我想运行一个查询来显示每年流派的数量,而不会因为Label列而重复计算。 我要这个:

Year, hip hop, pop-dance
1990, 1, 1

我必须运行什么查询才能得到我想要的?

因为您不能使用pivot ,所以您可以这样做。

select year,
count(distinct case when `Genre` = 'hip hop' then 1 end) as hiphop,
count(distinct case when `Genre` = 'pop-dance' then 1 end) as popdance
from tbl
group by year

接受的答案对我有用。

我在这里添加了一个更复杂的案例,如果有人需要,加入。

也可以看看:

将两个 SQL 查询的结果组合为单独的列

我的例子:

    select Info.*, Roots.*, ColeColeFit.*, f10.*, f20k.*
    from Info
    join (select * from Data where Frequency = 10) as f10
      on f10.Info_ID = Info.id
    join (select * from Data where Frequency = 20000) as f20k
      on f20k.Info_ID = Info.id
    join Roots
      on Info.File_Num = Roots."Plant number"
    join ColeColeFit
      on ColeColeFit.id = Info.id

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM