Sql 如何连接和选择具有条件的表?

Sql 如何连接和选择具有条件的表?,sql,sql-server,database,Sql,Sql Server,Database,我有两个表,想加入并获得具有攻击性的求和字段 我的桌子是: 表中的“PriceListid”相同(联接字段) 所以,我想找到用户(“UserID”)和“Price”,但要使用“Type=0(查看)或1(单击)”,还要获得SUM(“ShowQuantity”)、SUM(“ClickQuantity”)和“Title”、“URL”,。。。 结果应按“UserID”分组 结果如下: 根据您评论中的新信息,可以使用主表查找哪些用户查看/单击了哪些产品多少次: select pl.userid

我有两个表,想加入并获得具有攻击性的求和字段

我的桌子是:

表中的“PriceListid”相同(联接字段)

所以,我想找到用户(“UserID”)和“Price”,但要使用“Type=0(查看)或1(单击)”,还要获得SUM(“ShowQuantity”)、SUM(“ClickQuantity”)和“Title”、“URL”,。。。 结果应按“UserID”分组

结果如下:


根据您评论中的新信息,可以使用主表查找哪些用户查看/单击了哪些产品多少次:

select 
    pl.userid, 
    pl.PriceListId, 
    pl.offerid,
    sum(case when pl.type = 0 then 1 else 0 end) as 'times_viewed',
    sum(case when pl.type = 1 then 1 else 0 end) as 'times_clicked'
from PriceList pl
group by pl.userid, pl.PriceListId, pl.offerid
having sum(case when pl.type = 1 then 1 else 0 end) > 0
然后展开此基本查询,您可以连接到第二个表,以获取
标题
url

select 
    pl.userid, 
    pl.pricelistid, 
    pl.offerid,
    sum(case when pl.type = 0 then 1 else 0 end) as 'times_viewed',
    sum(case when pl.type = 1 then 1 else 0 end) as 'times_clicked',
    max(pld.Title) as 'Title',
    max(pld.URL) as 'URL',
    max(pld.Model) as 'Name'
from PriceList pl
inner join PriceListDetails pld on pld.OfferId = pl.OfferId and pld.pricelistid = pl.pricelistid
group by pl.userid, pl.pricelistid, pl.offerid
having sum(case when pl.type = 1 then 1 else 0 end) > 0
要进一步筛选此项以仅显示
PriceListId
符合您的评论中所述的某些条件的记录,此项功能应起作用:

select 
    pl.userid, 
    pl.pricelistid, 
    pl.offerid,
    sum(case when pl.type = 0 then 1 else 0 end) as 'times_viewed',
    sum(case when pl.type = 1 then 1 else 0 end) as 'times_clicked',
    max(pld.Title) as 'Title',
    max(pld.URL) as 'URL',
    max(pld.Model) as 'Name'
from PriceList pl
inner join PriceListDetails pld on pld.OfferId = pl.OfferId and pld.pricelistid = pl.pricelistid
where pl.pricelistid in (
    select articleid
    from c
    where c.state = 2
    and c.Created >= datediff(dd,0,getdate())
)
group by pl.userid, pl.pricelistid, pl.offerid
having sum(case when pl.type = 1 then 1 else 0 end) > 0

表名是什么?在这两个表中的图像价格列中。感谢您的回复,关于更多信息,我附上了我的数据的2个屏幕截图:第一个您命名为“pl”表,第二个屏幕截图是“pld”。因此,正如您所看到的,我想找到查看“A”并单击“A”的用户(“userID”)(“A在这里是“PriceListId”-和字段“Type”由0组成,用于查看和单击1),并且我还希望查找(计数)同一列的查看次数(“offerid”)。例如,用户X可能会被访问4次(相同的“offerid”)但只点击了一次。我附上了另一个屏幕截图,关于我在上一条评论中解释的内容,这是针对一个用户的!正如您所看到的,我想知道这个用户(主表中的所有用户)在同一个“offerId”上访问了多少次,并点击了多少次!在这个屏幕截图中,结果将是“offerId 9041-1次查看1次点击1次”“或者对于offerid=93359,2次浏览1次点击-@yadishahryary我已经根据您的评论更新了我的答案,请让我知道这是否更接近您的需要。非常感谢您,但第一个脚本工作正常,因为根据我的屏幕截图,结果是正确的,但当我想从表('pld')中选择“标题”和“Url”等时,请告知我)当我执行你的第二个脚本时,我得到了截图,这是错误的!('times view'和'times clicked')!如果我们加入“奥菲丽”,你觉得怎么样?在两个表中有相同的内容,我们在您的第一个脚本中找到了!!我再次共享了完整的表结构-(左一个是“pl”,右一个是“pld”)。Thanks@yadishahryary啊,好吧,那是因为在“pld”中,同一个
PriceListId
有多条记录。我之前没发现。OfferId在“pld”中是唯一的吗?那么,是的,加入OfferId将给出正确的结果。尝试更新的第二个查询。